-
Notifications
You must be signed in to change notification settings - Fork 2
/
MaxPoints.java
46 lines (43 loc) · 1.41 KB
/
MaxPoints.java
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
package src.java.hard.math;
import java.util.HashMap;
class Point {
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
public class MaxPoints {
public int maxPoints(Point[] points) {
if (points == null || points.length==0)
return 0;
int max = 0;
for(int i = 0; i<points.length; i++){
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
int duplicate = 1;
for(int j=i+1; j<points.length; j++){
if (points[i].x == points[j].x && points[i].y == points[j].y){
duplicate++;
continue;
}
double slope;
if (points[i].x == points[j].x)
slope = Integer.MAX_VALUE;
else
slope = points[i].y == points[j].y ? 0 : 1.0 * (points[i].y - points[j].y)/(points[i].x - points[j].x);
if (map.containsKey(slope)){
int count = map.get(slope)+1;
map.put(slope, count);
}
else{
map.put(slope, 1);
}
}
int tempMax = 0;
for(double slope : map.keySet()){
tempMax = Math.max(map.get(slope), tempMax);
}
max = Math.max(tempMax+duplicate, max);
}
return max;
}
}