forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_149.java
85 lines (79 loc) · 3.38 KB
/
_149.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.fishercoder.solutions;
import com.fishercoder.common.classes.Point;
/**
* Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
*/
public class _149 {
public int maxPoints(Point[] points) {
int max = 0;
if (points.length == 0) {
max = 0;
} else if (points.length == 1) {
max = 1;
} else if (points.length == 2) {
max = 2;
} else if (points.length == 3) {
max = 2;
if ((points[0].x - points[1].x) * (points[1].y - points[2].y) == (points[0].y - points[1].y)
* (points[1].x - points[2].x)) {
max++;
}
} else {
int[][] maxPoints = new int[points.length][points.length];
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length && j != i; j++) {
maxPoints[i][j] = 2;
// System.out.print(maxPoints[i][j] + " ");
}
}
for (int i = 0; i < points.length; i++) {
for (int j = 0; (j < points.length) && (j != i); j++) {
if (((points[i].x == points[j].x) && (points[i].y == points[j].y))) {
for (int k = 0; (k < points.length); k++) {
if ((k != i) && (k != j)) {
if (((points[k].x == points[i].x) && (points[k].y == points[i].y))) {
maxPoints[i][j]++;
}
}
}
} else {
for (int k = 0; (k < points.length); k++) {
/*
* Here, I must put the judgment (k!=i) && (k!=j) in the
* if statement instead of in the for, otherwise, when k
* equals i or j, it will stop traversing the rest of
* the points that k represents!
*
* This is the key to solving this problem and Siyuan
* Song helped me spot this error!
*
* It took me an hour and couldn't find any clue!
*/
if ((k != i) && (k != j)) {
if (((points[k].x == points[i].x) && (points[k].y == points[i].y))) {
maxPoints[i][j]++;
} else if (((points[k].x == points[j].x) && (points[k].y == points[j].y))) {
maxPoints[i][j]++;
} else if ((points[i].x - points[j].x)
* (points[k].y - points[j].y) == (points[i].y - points[j].y)
* (points[k].x - points[j].x)) {
maxPoints[i][j]++;
}
}
}
}
}
}
for (int m = 0; m < points.length; m++) {
for (int n = 0; n < points.length; n++) {
if (maxPoints[m][n] > max) {
// System.out.print("maxPoints[" + m + "][" + n +"]:" +
// maxPoints[m][n] + "\t");
max = maxPoints[m][n];
}
}
}
}
return max;
}
}