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.
难度:hard
Solution: Hashtable
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
int maxNumPoints = 0;
for(int i = 0; i < points.length; ++i) {
Map<String, Integer> map = new HashMap<>();
int duplicates = 0, maxCount = 0;
for(int j = 0; j < points.length; ++j) {
int x = points[i].x - points[j].x;
int y = points[i].y - points[j].y;
if(x == 0 && y == 0) {
++duplicates;
} else if(x == 0 && y != 0) {
String key = 0 + " " + 1;
int count = map.containsKey(key) ? map.get(key) + 1 : 1;
map.put(key, count);
maxCount = Math.max(maxCount, count);
} else if(x != 0 && y == 0) {
String key = 1 + " " + 0;
int count = map.containsKey(key) ? map.get(key) + 1 : 1;
map.put(key, count);
maxCount = Math.max(maxCount, count);
} else {
int r = gcd(x, y);
x /= r;
y /= r;
String key = x + " " + y;
int count = map.containsKey(key) ? map.get(key) + 1 : 1;
map.put(key, count);
maxCount = Math.max(maxCount, count);
}
}
maxNumPoints = Math.max(maxNumPoints, maxCount + duplicates);
}
return maxNumPoints;
}
private int gcd(int p, int q) {
if(q == 0) {
return p;
}
int r = p % q;
return gcd(q, r);
}
}