1. 程式人生 > >LeetCode 149. Max Points on a Line

LeetCode 149. Max Points on a Line

lan res gin max leetcode cto ica pub def

今天手殘,碰了一道leetcode HARD難度題目,果然來著不善,花了不少時間,題目很簡單,求平面內一些離散點中,最大共線點的數量。最直接的思路就是通過斜率判斷,但是考慮到斜率很可能是小數,比較小數的大小會有誤差,因此我們不做除法,取橫縱坐標差值的最大公約數,然後橫縱坐標分別除以最大公約數即可,這樣一來斜率相同的點就可以在哈希表中的同一個映射中,比如(1,2)(2,4)(4,8),最後都映射到索引為<1,2>的單元格中

我居然在訪問哈希表begin()時忘記把括括號寫成中文的了,被自己蠢哭了!!!

代碼如下:

 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 int res = 0; 14 for (int i = 0; i < points.size(); ++i) {
15 map<pair<int, int>, int> m; 16 int duplicate = 1; 17 for (int j = i + 1; j < points.size(); ++j) { 18 if (points[i].x == points[j].x && points[i].y == points[j].y) { 19 ++duplicate; continue; 20 }
21 int dx = points[j].x - points[i].x; 22 int dy = points[j].y - points[i].y; 23 int d = gcd(dx, dy); 24 ++m[{dx / d, dy / d}]; 25 } 26 res = max(res, duplicate); 27 for (auto it = m.begin(); it != m.end(); ++it) { 28 res = max(res, it->second + duplicate); 29 } 30 } 31 return res; 32 } 33 int gcd(int a, int b) { 34 return (b == 0) ? a : gcd(b, a % b); 35 } 36 };

更多解法參考 http://www.cnblogs.com/grandyang/p/4579693.html

LeetCode 149. Max Points on a Line