Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
标签
类似题目
思路:注意可能存在重合点,除去重合点,只要记录能够表示一条直线的(x0,y0),其中a=x1-x2和y1-y2的最大公约数,x0=(x1-x2)/a,y0=(y1-y2)/a。注意到对于特定的i0,只要第一次出现(x0,y0),那么在直线(x0,y0)的点的数量一定可以在i0下得到最大值,本质上就是比较每个i下第一次出现的(x0,y0)包含的点的数目。
代码:
1 /** 2 * Definition for a point. 3 * class Point { 4 * int x; 5 * int y; 6 * Point() { x = 0; y = 0; } 7 * Point(int a, int b) { x = a; y = b; } 8 * } 9 */ 10 public class Solution { 11 public int maxPoints(Point[] points) { 12 HashMap<Integer, Map<Integer, Integer>> hashMap = new HashMap<Integer, Map<Integer, Integer>>(); 13 int res = 0, maxCount = 0, overlap = 0; 14 for (int i = 0; i < points.length; ++i) { 15 hashMap.clear(); 16 maxCount = overlap = 0; 17 for (int j = i + 1; j < points.length; j++) { 18 int x = points[i].x - points[j].x; 19 int y = points[i].y - points[j].y; 20 if (x == 0 && y == 0) {//重合点 21 overlap++; 22 continue; 23 } 24 int gcd = Gcd(x, y); 25 x = x / gcd; 26 y = y / gcd; 27 if (hashMap.containsKey(x)) { 28 hashMap.get(x).put(y, hashMap.get(x).getOrDefault(y, 0) + 1); 29 }else { 30 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 31 map.put(y, 1); 32 hashMap.put(x, map); 33 } 34 maxCount = Math.max(maxCount, hashMap.get(x).get(y)); 35 } 36 res = Math.max(res, maxCount + overlap + 1); 37 } 38 return res; 39 } 40 private int Gcd(int x, int y){ 41 if (y == 0) return x; 42 return Gcd(y, x%y); 43 } 44 }