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.

分析:首先要注意的是,輸入數組中可能有重復的點。由於兩點確定一條直線,一個很直觀的解法是計算每兩個點形成的直線,然后把相同的直線合並,最后包含點最多的直線上點的個數就是本題的解。我們知道表示一條直線可以用斜率和y截距兩個浮點數(垂直於x軸的直線斜率為無窮大,截距用x截距),同時還需要保存每條直線上的點(避免重復)。聽起來就很麻煩,但是基於這個思想有一種簡單的實現方式:

  • 以某點O為中心,計算它和其他點的斜率,如果有兩個點A、B和O點形成的斜率相等,那么ABO三點是共線的,如果有多個點和O的斜率相等,那么這多個點和O也是共線的,因此我們可以求出包含O的所有直線中點數最多的直線,會得到一個最大共線點數k(O),如果和O點重復的點有n個(除了O本身),那么K(O) = K(O) + n。這一步的計算中,為了提高效率,我們可以用哈希表來保存某個斜率對應的點的數目。
  • 對數組中的每一個點i,按照第一步計算得到每個點最大點數K(i)
  • 從k(i)中選取最大的就是本題的解
  • 注意:為了避免重復計算,以數組中第i個點為中心時,只計算數組中它右邊的所有點                                                                                                                  本文地址
 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         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         int len = points.size(), res = 1;
16         if(len == 0)return 0;
17         unordered_map<double, int> umap;
18         for(int i = 0; i < len; i++)
19         {
20             umap.clear();
21             int samePointNum = 0,tmpres = 1;
22             for(int j = i+1; j < len; j++)
23             {
24                 double slope = std::numeric_limits<double>::infinity();//斜率初始化為無窮大,我們視橫坐標相同的兩點間的斜率為無窮大
25                 if(points[i].x != points[j].x)
26                     slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);
27                 else if(points[i].y == points[j].y)
28                     {samePointNum++; continue;}
29                 int tmp;
30                 if(umap.find(slope) != umap.end())
31                     tmp = ++umap[slope];
32                 else 
33                 {
34                     umap.insert(unordered_map<double, int>::value_type(slope, 2));
35                     tmp = 2;
36                 }
37                 if(tmpres < tmp)tmpres = tmp;
38             }
39             if(res < tmpres + samePointNum)res = tmpres + samePointNum;
40         }
41         return res;
42     }
43 };

【版權聲明】轉載請注明出處:http://www.cnblogs.com/TenosDoIt/p/3444086.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM