Max Points on a Line

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

 

 

 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         int N = points.size();
14         if (N < 3) return N;
15         unordered_map<int, int> tb;
16         int res = 0;
17         for (int i = 0; i < N; i++) {
18             tb.clear();
19             int o = 0, u = 0, v = 0;
20             for (int j = i; j < N; j++) {
21                 int x = points[j].x - points[i].x, y = points[j].y - points[i].y;
22                 if (x == 0 && y == 0) o++;
23                 else if (x == 0) v++;
24                 else u = max(u, ++tb[1e6*y / x]);
25             }
26             res = max(res, o + max(u, v));
27         }
28         return res;
29     }
30 };

 

posted @ 2014-04-24 11:16  beehard  阅读(122)  评论(0编辑  收藏  举报