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

找出在同一条直线上最多点的数量。

思路:本题可以直接根据斜率做个映射表,但是斜率就有精度问题,因此为了保证精度,可以通过biasX,biasY来表示一条直线的斜率。同一斜率对应点的数量通过一个Map<Integer, Map<Integer, Integer>> map来表示,第一个Integer表示biasX,第二个Integer表示biasY,第三个Integer表示该斜率对应的点数。

程序如下所示:

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
class Solution {
    public int maxPoints(Point[] points) {
        int len = points.length;
        if (len == 0){
            return 0;
        }
        int count = 1;
        for (int i = 0; i < len; ++ i){
            int samePoints = 0;
            int cur = 1;
            Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
            for (int j = i + 1; j < len; ++ j){
                if (points[j].x == points[i].x && points[j].y == points[i].y){
                    samePoints ++;
                    continue;
                }
                int biasX = points[j].x - points[i].x;
                int biasY = points[j].y - points[i].y;
                int g = gcd(biasX, biasY);
                biasX /= g;
                biasY /= g;
                int t = 0;
                if (!map.containsKey(biasX)){
                    Map<Integer, Integer> tmpMap = new HashMap<>();
                    tmpMap.put(biasY, 2);
                    map.put(biasX, tmpMap);
                    t = 2;                   
                }
                else {
                    Map<Integer, Integer> tmpMap = map.get(biasX);
                    if (tmpMap.containsKey(biasY)){
                        t = tmpMap.get(biasY);
                        t ++;
                        tmpMap.put(biasY, t);
                        map.put(biasX, tmpMap);
                    }
                    else {
                        tmpMap.put(biasY, 2);
                        map.put(biasX, tmpMap);
                        t = 2; 
                    }
                }
                cur = Math.max(cur, t);
            }
            count = Math.max(count, cur + samePoints);
        }
        return count;
    }
    
    public int gcd(int a, int b){
        if (b == 0){
            return a;
        }
        return gcd(b, a%b);
    }
}

猜你喜欢

转载自blog.csdn.net/excellentlizhensbfhw/article/details/80933880