题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:
(1)两点确定一条直线
(2)斜率相同的点落在一条直线上
(3)坐标相同的两个不同的点 算作2个点
使用Hashmap来存放键值对,Key用来存放斜率,value存放该斜率下的点的个数,对每个点进行循环遍历,计算该点和其余各个点的斜率,然后更新Hashmap中对应的值,每个点都计算出点数最大的值,保存在局部变量localmax中,维护一个全局变量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 }