Leetcode 149.直线上最多的点数
直线上最多的点数
给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
解释:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
示例 2:
输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
1 class Solution { 2 public int maxPoints(Point[] points) { 3 if(points.length == 0) { 4 return 0; 5 } 6 int[] count = new int[points.length]; 7 for (int i = 0; i < points.length; i++) { 8 count[i] = 1; 9 int size = 1; 10 int same = 0; 11 HashMap<Integer[], Integer> hashMap = new HashMap<>(); 12 for (int j = 0; j < points.length; j++) { 13 if(i != j) { 14 if(points[i].x != points[j].x) { 15 int dy = points[i].y - points[j].y; 16 int dx = points[i].x - points[j].x; 17 int gcd = generateGCD(dy, dx); 18 if(gcd != 0) { 19 dy = dy / gcd; 20 dx = dx / gcd; 21 } 22 Integer[] nums = new Integer[2]; 23 nums[0] = dy; 24 nums[1] = dx; 25 boolean flag = false; 26 for (Integer[] array : hashMap.keySet()) { 27 if(nums[0] == array[0] && nums[1] == array[1]) { 28 flag = true; 29 hashMap.put(array, hashMap.get(array) + 1); 30 } 31 } 32 if(!flag) { 33 hashMap.put(nums, 1); 34 } 35 }else { 36 if(points[i].y == points[j].y) { 37 same++; 38 } 39 size++; 40 } 41 } 42 } 43 for (Integer[] array : hashMap.keySet()) { 44 if(hashMap.get(array) + 1 > count[i]) { 45 count[i] = hashMap.get(array) + 1; 46 } 47 } 48 count[i] += same; 49 count[i] = Math.max(count[i], size); 50 } 51 int maxIndex = 0; 52 for (int i = 1; i < count.length; i++) { 53 if(count[i] > count[maxIndex]) { 54 maxIndex = i; 55 } 56 } 57 return count[maxIndex]; 58 } 59 60 // 欧几里得算法:计算最大公约数 61 private int generateGCD(int x, int y) { 62 if (y == 0) 63 return x; 64 return generateGCD(y, x % y); 65 } 66 }