## Monday, December 2, 2013

### [LeetCode] Max Points on a Line, Solution

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
[Thoughts]

y = ax + b

y1 = kx1 +b
y2 = kx2 +b

[Code]
``````1:       int maxPoints(vector<Point> &points) {
2:            unordered_map<float, int> statistic;
3:            int maxNum = 0;
4:            for (int i = 0; i< points.size(); i++)
5:            {
6:                 statistic.clear();
7:                 statistic[INT_MIN] = 0; // for processing duplicate point
8:                 int duplicate = 1;
9:                 for (int j = 0; j<points.size(); j++)
10:                 {
11:                      if (j == i) continue;
12:                      if (points[j].x == points[i].x && points[j].y == points[i].y) // count duplicate
13:                      {
14:                           duplicate++;
15:                           continue;
16:                      }
17:                      float key = (points[j].x - points[i].x) == 0 ? INT_MAX :
18:                                     (float) (points[j].y - points[i].y) / (points[j].x - points[i].x);
19:                      statistic[key]++;
20:                 }
21:                 for (unordered_map<float, int>::iterator it = statistic.begin(); it != statistic.end(); ++it)
22:                 {
23:                      if (it->second + duplicate >maxNum)
24:                      {
25:                           maxNum = it->second + duplicate;
26:                      }
27:                 }
28:            }
29:            return maxNum;
30:       }
``````

1. 垂直曲线， 即斜率无穷大

2. 重复节点。