給定一個二維平面,平面上有 n 個點,求最多有多少個點在同一條直線上。數據結構
示例 1:spa
輸入: [[1,1],[2,2],[3,3]] 輸出: 3 解釋: ^ | | o | o | o +-------------> 0 1 2 3 4
示例 2:code
輸入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] 輸出: 4 解釋: ^ | | o | o o | o | o o +-------------------> 0 1 2 3 4 5 6
看到此題,第一想法是用一個數據結構來表示某一條直線,直線的表達式有y = ax + b ,那提取出 a和b是否是就能夠了,寫完發現還有x = 1這種直線。而後想經過hashmap來保存直線對應的點數,若是參數a和b是個1/3這種值,因爲精度問題,算出來的兩個直線的數據結構的hash值就不同,hashmap就是認爲是兩個key。 最後無奈換成分數表達式 y = (a1/a2)*x + b1/b2; b1/b2 = (a2*y - a1*x)/a2;這樣4個int變量,就能夠精確表示一條直線.固然,分數須要進行約分!
struct FPoint { int a1; int a2; int b1; int b2; FPoint() : a1(0), a2(0), b1(0), b2(0) {} FPoint(int _a1, int _a2) { if (_a1 * _a2 > 0) { a1 = abs(_a1); a2 = abs(_a2); } else { a1 = -1 * abs(_a1); a2 = abs(_a2); } b1 = 0; b2 = 1; } bool Contain(Point p)const { long long int t1 = 1L, t2 = 1L; t1 = t1 * p.y * (a2*b2); t2 = t2 * a1*b2*p.x + b1*a2; return a2 == 0 ? p.x == b1 / b2 : t1 == t2; } void Normal() { if (a1 == 0 && a2 == 0) { } else if (a1 == 0) a2 = 1; else if (a2 == 0) a1 = 1; else { int s = a1*a2 > 0 ? 1 : -1; a1 = abs(a1); a2 = abs(a2); int _gcd = GCD(a1, a2); a1 = s * a1 / _gcd; a2 = a2 / _gcd; if (b1 == 0) b2 = 1; else { s = b1*b2 > 0 ? 1 : -1; b1 = abs(b1); b2 = abs(b2); _gcd = GCD(b1, b2); b1 = s * b1 / _gcd; b2 = b2 / _gcd; } } }
//最大公約數 int GCD(int a, int b){ int m = a, n = b, r; if (m < n){ int temp = m; m = n; n = temp; } r = m % n; while (r){ m = n; n = r; r = m % n; } return n; } }; struct RecordHash { size_t operator()(const FPoint& f) const{ return hash<int>()(f.a1) ^ hash<int>()(f.a2) ^ hash<int>()(f.b1) ^ hash<int>()(f.b2); } }; struct RecordCmp { bool operator()(const FPoint& f1, const FPoint& f2) const{ return f1.a1 == f2.a1 && f1.a2 == f2.a2 &&f1.b1 == f2.b1&&f1.b2 == f2.b2; } }; class Solution { public: FPoint GetPoint(Point a, Point b) { FPoint f(b.y - a.y, b.x - a.x ); if (f.a2 == 0) { f.b1 = a.x; f.b2 = 1; } else { f.b1 = (f.a2*a.y - f.a1*a.x); f.b2 = f.a2; } return f; } int maxPoints(vector<Point>& points) { if (points.size() <= 1) { return points.size(); } unordered_set<int> index_set; unordered_map<FPoint, int, RecordHash, RecordCmp> line_map; int max_point = 0; for (int i = 0; i < points.size(); i++) { unordered_map<FPoint, int, RecordHash, RecordCmp>::iterator itr = line_map.begin(); for (; itr != line_map.end(); itr++) { if (itr->first.Contain(points[i])) { itr->second++; max_point = max(max_point, itr->second); if (index_set.count(i) == 0)index_set.insert(i); } } for (int r = 0; r < points.size() ; r++) { if (r != i && index_set.count(r) == 0) { FPoint f = GetPoint(points[i], points[r]); f.Normal(); if (line_map[f] == 0) { line_map[f]++; } if (index_set.count(i) == 0) { index_set.insert(i); } max_point = max(max_point, line_map[f]); } } } return max_point; } };