-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxPointsOnALine.java
More file actions
62 lines (56 loc) · 1.22 KB
/
MaxPointsOnALine.java
File metadata and controls
62 lines (56 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.Point;
import java.util.HashMap;
/**
* @author Dectinc
* @version Apr 16, 2015 10:46:55 PM
*
*/
public class MaxPointsOnALine {
public int maxPoints(Point[] points) {
int numPoints = points.length;
if (numPoints < 2) {
return numPoints;
}
int max = 0;
HashMap<Double, Integer> slopeMap;
int vertical, samePoint;
for (int i = 0; i < numPoints; i++) {
Point curPoint = points[i];
slopeMap = new HashMap<Double, Integer>();
vertical = 0;
samePoint = 1;
for (int j = 0; j < numPoints; j++) {
if (j == i) {
continue;
}
Point point = points[j];
if (point.x == curPoint.x) {
if (point.y == curPoint.y) {
samePoint++;
} else {
vertical++;
}
} else {
double slope = ((double) point.y - curPoint.y)
/ (point.x - curPoint.x);
if (slopeMap.containsKey(slope)) {
slopeMap.put(slope, slopeMap.get(slope) + 1);
} else {
slopeMap.put(slope, 1);
}
}
}
for (Integer num : slopeMap.values()) {
max = Math.max(num + samePoint, max);
}
max = Math.max(vertical + samePoint, max);
}
return max;
}
public static void main(String[] args) {
}
}