forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxPointsOnALine.java
46 lines (45 loc) · 1.38 KB
/
MaxPointsOnALine.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
/*
Author: Andy, [email protected]
Date: Dec 03, 2014
Problem: Max Points On a Line
Difficulty: Easy
Notes:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution: 1. hashmap. Time: O(n^2), Space: O(n);
*/
/**
* 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 res = 0;
int N = points.length;
for (int i = 0; i < N; ++i) {
HashMap<Double, Integer> m = new HashMap<Double, Integer>();
int ss = 1, sp = 0;
for (int j = i + 1; j < N; ++j) {
double slope = Double.MIN_VALUE;
if (points[i].x != points[j].x) {
slope = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x);
if (slope == -0.0) slope = 0.0;
} else if (points[i].y == points[j].y) {
sp += 1; continue;
}
int tmp = 2;
if (m.containsKey(slope)) {
tmp = m.get(slope) + 1;
}
m.put(slope, tmp);
ss = Math.max(ss, tmp);
}
res = Math.max(res, ss + sp);
}
return res;
}
}