1 class Solution {
2 public:
3 int maxPoints(vector<Point> &points) {
4 unsigned n = points.size();
5 if (n <= 2)
6 return n;
7 unsigned maxLen = 2;
8 unordered_map<int, unsigned> xLines;
9 unordered_map<int, unsigned> yLines;
10 //consider situation of x and y;
11 for (auto iter = points.begin(); iter != points.end(); iter++){
12 if (xLines.find(iter->x) == xLines.end())
13 xLines[iter->x] = 1;
14 else xLines[iter->x]++;
15 maxLen = maxLen >= xLines[iter->x] ? maxLen : xLines[iter->x];
16 if (yLines.find(iter->y) == yLines.end())
17 yLines[iter->y] = 1;
18 else yLines[iter->y]++;
19 maxLen = maxLen >= yLines[iter->y] ? maxLen : yLines[iter->y];
20 }
21 vector<unordered_set<double> > slopes(n,unordered_set<double>());
22 for (unsigned i = 0; i < n - 1 && n-i>maxLen; i++){
23 unsigned startLen = 2;
24 for (unsigned j = i + 1; j <=n-1&&n-j+startLen-1>maxLen; j++){
25 int dx = points[j].x - points[i].x;
26 int dy = points[j].y - points[i].y;
27 if (dx == 0 && dy == 0)
28 startLen++;
29 if (dx == 0 || dy == 0)
30 continue;
31 double sl = ((double)dy) / ((double)dx);
32 if (slopes[j].find(sl) != slopes[j].end())
33 continue;
34 slopes[j].insert(sl);
35 unsigned curLen = startLen;
36 for (unsigned k = j + 1; k < n && curLen+n-k>maxLen; k++){
37 int ddx = points[k].x - points[i].x;
38 int ddy = points[k].y - points[i].y;
39 if (ddx == 0 && ddy == 0)
40 curLen++;
41 if (ddx == 0 || ddy == 0)
42 continue;
43 double ssl = ((double)ddy) / ((double)ddx);
44 if (ssl != sl)
45 continue;
46 curLen++;
47 slopes[k].insert(sl);
48 }
49 maxLen = maxLen >= curLen ? maxLen : curLen;
50 }
51 }
52 return maxLen;
53 }
54 };