[LC] 149. 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.

class Solution {
    public int maxPoints(int[][] points) {
       if (points == null || points.length == 0) {
           return 0;
       }
        int count = 0;
        for (int i = 0; i < points.length; i++) {
            Map<String, Integer> map = new HashMap<>();
            int samePoints = 0;
            int sameX = 1;
            for (int j = 0;  j < points.length; j++) {
                if (j != i) {
                        if (points[j][0] == points[i][0] && points[j][1] == points[i][1]) {
                        samePoints += 1;
                    }
                    if (points[j][0] == points[i][0]) {
                        sameX += 1;
                        continue;
                    }
                    int denominator = points[i][0] - points[j][0];
                    int numerator = points[i][1] - points[j][1];
                    int gcd = getGCD(numerator, denominator);
                    String hashStr = (numerator / gcd) + "/" + (denominator / gcd);
                    map.put(hashStr, map.getOrDefault(hashStr, 1) + 1);
                    count = Math.max(count, map.get(hashStr) + samePoints);
                }
            }
            count = Math.max(count, sameX);
        }
        return count;
    }
    
    private int getGCD(int a, int b) {
        if (a == 0) {
            return b;
        }
        return getGCD(b % a, a);
    }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12181847.html
今日推荐