[关闭]
@zimenglan 2014-11-29T11:23:12.000000Z 字数 1171 阅读 1026

Max Points on a Line

leetcode


Max Points on a Line

题目链接


题目大意:

给定一些点(二维)的集合, 找出位于同一条直线的点的个数的最大值

Code
reference

  1. /**
  2. * Definition for a point.
  3. * struct Point {
  4. * int x;
  5. * int y;
  6. * Point() : x(0), y(0) {}
  7. * Point(int a, int b) : x(a), y(b) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int maxPoints(vector<Point> &points) {
  13. double slope;
  14. int maxNum = 0;
  15. double nSlope;
  16. int size = points.size();
  17. // if the number of the points is less than 3
  18. // then directly return it
  19. // since more than 1 point makes a line
  20. if(size < 3) {
  21. return size;
  22. }
  23. for(int i = 0; i < size; i++) {
  24. int rep = 0;
  25. // slope -> count
  26. std::map<double, int> lines;
  27. for(int j = 0; j < size; j++) {
  28. if(i == j) {
  29. continue;
  30. }
  31. // replication
  32. if(points[i].x == points[j].x
  33. && points[i].y == points[j].y) {
  34. rep++;
  35. continue;
  36. }
  37. // x1 == x2
  38. // in this case, it can compute the slope
  39. // which is oo (infinity)
  40. // so use INT_MIN or INT_MAX to record this case
  41. // here use INT_MIN
  42. if(points[i].x == points[j].x) {
  43. lines[INT_MIN]++;
  44. } else {
  45. slope = (points[i].y - points[j].y)
  46. / (points[i].x - points[j].x + 0.);
  47. lines[slope]++;
  48. }
  49. }
  50. // statistic & maybe lines is empty
  51. if(lines.size() == 0) {
  52. maxNum = max(maxNum, rep);
  53. continue;
  54. }
  55. // statistic
  56. std::map<double, int>::iterator iter;
  57. for(iter = lines.begin(); iter != lines.end(); iter++) {
  58. if(iter->second + rep > maxNum) {
  59. maxNum = iter->second + rep;
  60. nSlope = iter->first;
  61. }
  62. }
  63. }
  64. // don't forget that plus the point itself
  65. return maxNum + 1;
  66. }
  67. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注