码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-11 22:40:44      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

 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 };

 

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

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4639369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!