原题链接在这里:https://leetcode.com/problems/max-points-on-a-line/
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4 Explanation: ^ | | o | o o | o | o o +-------------------> 0 1 2 3 4 5 6
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
题解:
Given a 2D board, return the maximum points on the same line.
From each point i, get the slope from this point i and connecting all other points.
If slop are equal from 2 other points and of cource line goes through the current point i, then 3 points fall on the same line.
If coordinates are equal, they would be treated as 2 different point.
Then for each point i, we have a HashMap<String, Integer> to accumlate mutiplicity of nodes on the same line.
Key String is dx + "," + dy representing slope. Of cource dx and dy are already divided by greatest common divisor.
Then the max points count from the current point i, would be max(multiplicity) + dup.
Time Complexity is O(n^2). n = points.length.
Space is O(n).
AC Java:
1 class Solution { 2 public int maxPoints(int[][] points) { 3 if(points == null){ 4 return 0; 5 } 6 7 int n = points.length; 8 if(n <= 2){ 9 return n; 10 } 11 12 int res = 0; 13 14 for(int i = 0; i < n; i++){ 15 HashMap<String, Integer> countMap = new HashMap<>(); 16 int dup = 1; 17 int maxFromThisPoint = 0; 18 19 for(int j = i + 1; j < n; j++){ 20 int dx = points[j][0] - points[i][0]; 21 int dy = points[j][1] - points[i][1]; 22 if(dx == 0 && dy == 0){ 23 dup++; 24 continue; 25 } 26 27 int gcd = getGcd(dx, dy); 28 dx /= gcd; 29 dy /= gcd; 30 String key = dx + "," + dy; 31 countMap.put(key, countMap.getOrDefault(key, 0) + 1); 32 maxFromThisPoint = Math.max(maxFromThisPoint, countMap.get(key)); 33 } 34 35 res = Math.max(res, maxFromThisPoint + dup); 36 } 37 38 return res; 39 } 40 41 private int getGcd(int x, int y){ 42 if(y == 0){ 43 return x; 44 } 45 46 return getGcd(y, x % y); 47 } 48 }