題目描述:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.算法
解題思路:題目說的很是清楚,尋找二維點在一條直線上的最大數目。網絡
思路一:ide
首先想到的方式就是直接法,遍歷每一個節點,一個節點下,遍歷一遍,肯定一條直線後,再遍歷一遍肯定這條直線上的次數,這樣的話,時間複雜度就是O(n3)。感受在OJ上會跪,就不寫了//不過看到劉斌的博客,貌似是能夠AC的學習
思路二:spa
既然直接法太複雜的話,咱們接着思考其餘方法。我想到能夠用直線的斜率k描述一條直線,把全部的點的直線搭配的斜率計算出來,存儲起來,最後找到斜率出現最多的次數,就對應點最多的直線。code
考慮使用map,創建斜率k和出現次數的映射,最後取出最大的次數便可。其中須要處理,兩個點相等以及斜率不存在(即橫座標相等的狀況)blog
代碼:leetcode
1 class Solution { 2 public: 3 int maxPoints(vector<Point>& points) { 4 map<double,int> slope; //創建斜率與出現次數的映射 5 if(points.size() <= 2) //點的個數小於3時,直接返回點的個數 6 return points.size(); 7 int n = points.size(),ans = 0; //ans爲最終結果 8 for(int i = 0; i < n - 1; i++) 9 { 10 int maxNum = 0; //記錄當前節點對應的斜率出現最多的次數 11 int same_x = 1; //記錄斜率不存在,即橫座標相等的狀況 12 int samePoint = 0; //記錄重合的點 13 slope.clear(); 14 for(int j = i + 1; j < n; j++) 15 { 16 17 if (i == j) 18 continue; 19 if (points[i].x == points[j].x && points[i].y == points[j].y) 20 { 21 samePoint++; 22 continue; 23 } 24 if (points[i].x == points[j].x) //斜率不存在 25 { 26 same_x++; 27 continue; 28 } 29 double k = (double)(points[i].y-points[j].y)/(points[i].x-points[j].x); 30 if (slope.find(k) != slope.end()) //更新當前斜率出現的次數 31 slope[k]++; 32 else 33 slope[k] = 2; 34 } 35 for (map<double,int>::iterator it = slope.begin(); it != slope.end(); ++it) //找出最大次數的斜率 36 same_x = max(same_x,it->second); 37 maxNum = same_x + samePoint; 38 ans = max(ans,maxNum); //與以前的最大值比較 39 } 40 return ans; 41 } 42 };
在leetcode上提交,能夠AC,分析一下這個算法的複雜度,外層爲兩個循環,內層使用map求出最大值。時間複雜度爲O(n2)。博客
此博客中的內容均爲原創或來自網絡,不用作任何商業用途。歡迎與我交流學習,個人郵箱:lsa0924@163.comit