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

Max Points on a Line

时间:2014-09-28 10:50:31      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

题目描述:

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

解题方案:

该题想不到其他好办法,唯有暴力破解,两点求斜率,如果斜率相同,意味着共线,然后求出最大共线点数,注意可能有重复的点,和斜率为正无穷的点。下面是该题的代码:

 1 class Solution {
 2 public:
 3     int maxPoints(vector<Point> &points) {
 4         map<double, int> result;
 5         int max_line = 0;
 6         double gradient;//斜率
 7         int multi = 0;
 8         for (vector<Point>::iterator ix = points.begin(); ix != points.end(); ++ix) {
 9             result.clear();
10             multi = 1;
11             result[INT_MIN] = 0;
12             for (vector<Point>::iterator jx = points.begin(); jx != points.end(); ++jx) {
13                 if (ix == jx) {
14                     continue;
15                 }
16                 if(ix->x == jx->x && ix->y == jx->y){
17                     ++multi;
18                     continue;
19                 }
20                 if(ix->x != jx->x){
21                     gradient = (double)(ix->y - jx->y) / (ix->x - jx->x);
22                     result[gradient]++;
23                 }else{
24                     result[INT_MAX]++;
25                 }
26             }
27             for (map<double, int>::iterator ix = result.begin(); ix != result.end(); ++ix){
28                 if (ix->second + multi > max_line) {
29                     max_line = ix->second + multi;
30                 }
31             }
32         }
33         return max_line;
34     }
35 };

 

Max Points on a Line

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/skycore/p/3997677.html

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