Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
huahua:https://zxi.mytechroad.com/blog/geometry/leetcode-149-max-points-on-a-line/
思路:
两点确定一线后,如何判断第三点是否与他们共线?关键在于比较slope。如果两对点的slope一样,可以判断这两条线段共线。为了避免floating造成的误差,这里需要用pair
Time complexity: O(n^2)
Space complexity: O(n)
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int n = points.size();
int result = 0;
for (int i = 0; i < n; i++) {
map<pair<int, int>, int> hash;
int duplicates = 1;
int current = 0;
for (int j = i + 1; j < n; j++) {
if (points[i] == points[j]) duplicates++;
else {
pair<int, int> slope = getSlope(points[i], points[j]);
hash[slope]++;
current = max(current, hash[slope]);
}
}
result = max(result, current + duplicates);
}
return result;
}
pair<int, int> getSlope(vector<int> & a, vector<int> & b) {
// vertical line
if (a[0] == b[0]) return {a[0], 0};
// horizontal line
if (a[1] == b[1]) return {0, a[1]};
// find gcd
int d = gcd(a[1] - b[1], a[0] - b[0]);
// return normalized slope pair
return {(a[1] - b[1]) / d, (a[0] - b[0]) / d};
}
int gcd(int m, int n){
return (n == 0) ? m : gcd(n, m % n);
}
};