File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Date: Dec 03, 2014
4
+ Problem: Max Points On a Line
5
+ Difficulty: Easy
6
+ Notes:
7
+ Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
8
+ Solution: 1. hashmap. Time: O(n^2), Space: O(n);
9
+ */
10
+
11
+ /**
12
+ * Definition for a point.
13
+ * class Point {
14
+ * int x;
15
+ * int y;
16
+ * Point() { x = 0; y = 0; }
17
+ * Point(int a, int b) { x = a; y = b; }
18
+ * }
19
+ */
20
+ public class Solution {
21
+ public int maxPoints (Point [] points ) {
22
+ int res = 0 ;
23
+ int N = points .length ;
24
+ for (int i = 0 ; i < N ; ++i ) {
25
+ HashMap <Double , Integer > m = new HashMap <Double , Integer >();
26
+ int ss = 1 , sp = 0 ;
27
+ for (int j = i + 1 ; j < N ; ++j ) {
28
+ double slope = Double .MIN_VALUE ;
29
+ if (points [i ].x != points [j ].x ) {
30
+ slope = (double )(points [i ].y - points [j ].y ) / (points [i ].x - points [j ].x );
31
+ if (slope == -0.0 ) slope = 0.0 ;
32
+ } else if (points [i ].y == points [j ].y ) {
33
+ sp += 1 ; continue ;
34
+ }
35
+ int tmp = 2 ;
36
+ if (m .containsKey (slope )) {
37
+ tmp = m .get (slope ) + 1 ;
38
+ }
39
+ m .put (slope , tmp );
40
+ ss = Math .max (ss , tmp );
41
+ }
42
+ res = Math .max (res , ss + sp );
43
+ }
44
+ return res ;
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments