題目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
題解:
這道題就是給你一個2D平面,然後給你的資料結構是由橫縱座標表示的點,然後看哪條直線上的點最多。
(1)兩點確定一條直線
(2)斜率相同的點落在一條直線上
(3)座標相同的兩個不同的點 算作2個點
利用HashMap,Key值存斜率,Value存此斜率下的點的個數。同時考慮特殊情況,如果恰巧遍歷到一個相同座標的點,那麼就維護一個local的counter來記錄相同的點。
維護一個localmax,計算當前情況下的最大值;再維護一個全域性Max來計算總的最大值。
返回全域性Max即可。
程式碼如下:
1 public int maxPoints(Point[] points) {
2 if(points.length == 0||points == null)
3 return 0;
4
5 if(points.length == 1)
6 return 1;
7
8 int max = 1; //the final max value, at least one
9 for(int i = 0; i < points.length; i++) {
10 HashMap<Float, Integer> hm = new HashMap<Float, Integer>();
11 int same = 0;
12 int localmax = 1; //the max value of current slope, at least one
13 for(int j = 0; j < points.length; j++) {
14 if(i == j)
15 continue;
16
17 if(points[i].x == points[j].x && points[i].y == points[j].y){
18 same++;
19 continue;
20 }
21
22 float slope = ((float)(points[i].y - points[j].y))/(points[i].x - points[j].x);
23
24 if(hm.containsKey(slope))
25 hm.put(slope, hm.get(slope) + 1);
26 else
27 hm.put(slope, 2); //two points form a line
28 }
29
30 for (Integer value : hm.values())
31 localmax = Math.max(localmax, value);
32
33 localmax += same;
34 max = Math.max(max, localmax);
35 }
36 return max;
37 }
2 if(points.length == 0||points == null)
3 return 0;
4
5 if(points.length == 1)
6 return 1;
7
8 int max = 1; //the final max value, at least one
9 for(int i = 0; i < points.length; i++) {
10 HashMap<Float, Integer> hm = new HashMap<Float, Integer>();
11 int same = 0;
12 int localmax = 1; //the max value of current slope, at least one
13 for(int j = 0; j < points.length; j++) {
14 if(i == j)
15 continue;
16
17 if(points[i].x == points[j].x && points[i].y == points[j].y){
18 same++;
19 continue;
20 }
21
22 float slope = ((float)(points[i].y - points[j].y))/(points[i].x - points[j].x);
23
24 if(hm.containsKey(slope))
25 hm.put(slope, hm.get(slope) + 1);
26 else
27 hm.put(slope, 2); //two points form a line
28 }
29
30 for (Integer value : hm.values())
31 localmax = Math.max(localmax, value);
32
33 localmax += same;
34 max = Math.max(max, localmax);
35 }
36 return max;
37 }
Reference:
http://blog.csdn.net/ttgump/article/details/23146357
http://blog.csdn.net/linhuanmars/article/details/21060933