[LeetCode] 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.

经过同一个点且斜率相等的直线一定是同一条直线,所以我们只要分别计算每一个点与其它点的直线的斜率,统计斜率的个数,找出最大值。可以使用double来表示斜率,使用map<double, int>来统计个数。但是有两点要注意,那就是:

(1) 如果直线与x轴垂直,此时斜率是无穷大,要单独处理

(2) 所给的点中有些是相同的点,此时也要特殊处理一下。

 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 res = 0, same_cnt, ver_cnt, cnt;
14         unordered_map<double, int> mp;
15         double k;
16         for (int i = 0; i < points.size(); ++i) {
17             same_cnt = ver_cnt = cnt = 0;
18             mp.clear();
19             for (int j = 0; j < points.size(); ++j) {
20                 if (points[i].x == points[j].x) {
21                     if (points[i].y == points[j].y) {
22                         ++same_cnt; 
23                         continue;
24                     }else {
25                         ++ver_cnt;
26                         cnt = max(cnt, ver_cnt);
27                     }
28                 } else {
29                     k = (double) (points[i].y - points[j].y) / (points[i].x - points[j].x);
30                     ++mp[k];
31                     cnt = max(cnt, mp[k]);
32                 }
33             }
34             res = max(res, cnt + same_cnt);
35         }
36         return res;
37     }
38 };

 

posted @ 2015-05-25 14:32  Eason Liu  阅读(207)  评论(0编辑  收藏  举报