[LintCode] 最多有多少个点在一条直线上

 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     /**
13      * @param points an array of point
14      * @return an integer
15      */
16     int maxPoints(vector<Point>& points) {
17         // Write your code here
18         unordered_map<float, int> slopes;
19         int maxp = 0, n = points.size();
20         for (int i = 0; i < n; i++) {
21             slopes.clear();
22             int duplicate = 1;
23             for (int j = i + 1; j < n; j++) {
24                 if (points[i].x == points[j].x && points[i].y == points[j].y) {
25                     duplicate++;
26                     continue;
27                 }
28                 float slope = (points[i].x == points[j].x) ? INT_MAX:
29                               (float)(points[i].y - points[j].y) / (points[i].x - points[j].x);
30                 slopes[slope]++;
31             }
32             maxp = max(maxp, duplicate);
33             for (auto slope : slopes)
34                 if (slope.second + duplicate > maxp)
35                     maxp = slope.second + duplicate;
36         }
37         return maxp;
38     }
39 };
原文地址:https://www.cnblogs.com/jcliBlogger/p/4639369.html