149-Max Points on a Line

kevin聰發表於2018-04-24

Description

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

問題描述

在一個2維的平面上給定n個點, 返回在同一條直線上的最多的點的個數


問題分析

每輪以一個點為端點, 算出對應的在同一條直線上的最多的點的個數, 然後與當前的最大值比較即可


解法

/**
 * 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) {
        if(points.length <= 2)  return points.length;
        //儲存每輪的結果
        Map<Integer, Map<Integer, Integer>> map = new HashMap();

        int res = 0, len = points.length;
        for(int i = 0;i < len;i++){
            //每輪進行處理前先清空上一輪的結果
            map.clear();
            int x = points[i].x;
            int y = points[i].y;
            //重複的點的個數
            int overlap = 1;
            int max = 0;
            //注意這裡是i + 1
            for(int j = i + 1;j < len;j++){
                int kx = points[j].x;
                int ky = points[j].y;
                int dy = ky - y;
                int dx = kx - x;
                if(dy == 0 && dx == 0){
                    overlap++;
                    continue;
                }
                //通過最大公約數對斜率化簡
                int g = gcd(dy, dx);
                dy = dy / g;
                dx = dx / g;
                //如果有過相同斜率的點, 那麼在一條直線上
                if(map.containsKey(dy)){
                    map.get(dy).put(dx, map.get(dy).getOrDefault(dx, 0) + 1);
                }else{
                    Map<Integer, Integer> temp = new HashMap();
                    temp.put(dx, 1);
                    map.put(dy, temp);
                }
                max = Math.max(max, map.get(dy).get(dx));
            }
            //注意這裡需要加上overlap
            res = Math.max(res, overlap + max);
        }

        return res;
    }
    //求最大公約數
    public int gcd(int a, int b){
        if(b == 0)  return a;
        return gcd(b, a % b);
    }
}

相關文章