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

leetcode 149. Max Points on a Line

时间:2015-01-13 19:36:55      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

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

两层循环,将在同一直线上的点放入hash table,找到hash table中的最大值。

 1 int maxPoints(vector<Point> &points) 
 2     {
 3         int max_points = 0, duplicate = 0;
 4         unordered_map<float, int> htable;
 5         double slope = 0;
 6         int n = points.size();
 7         if (n <= 1)
 8             return n;
 9         
10         for (int i = 0; i < n; i++)
11         {
12             duplicate = 1;
13             htable.clear();
14             for (int j = i + 1; j < n; j++)
15             {
16                 if ((points[i].x == points[j].x) && (points[i].y == points[j].y))
17                 {    
18                     duplicate++;
19                     continue;
20                 }
21                 
22                 slope = (points[i].x == points[j].x) ? INT_MAX : (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
23                 htable[slope]++;
24             }
25             for (unordered_map<float, int>::iterator it = htable.begin(); it != htable.end(); it++)
26             {
27                 if (max_points < it->second + duplicate)
28                     max_points = it->second + duplicate;
29             }
30             max_points = max(max_points, duplicate);
31         }
32         
33         return max_points;
34     }

 

leetcode 149. Max Points on a Line

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4221870.html

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