leetcode149- Max Points on a Line- hard

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

 

考数学和抠细节。O(n2)。每对点都要遍历。先固定第一个点,从第一个点开始跟后面每个点计算斜率,存到斜率-计数的<Double,Integer>map里。每个点为起点的斜率遍历过了以后,打一下擂台(count + dup)。

细节:1.点重复(用dup计数,这个要加到所有斜率上面的)

2. 斜率为正无穷,用double(Integer.MAX_VALUE)计数

3. 斜率为0,用0计数(避免+-0情况)

4. 普通斜率(最好用GCD最小公倍数求一下然后存这个约分了的x-y-计数对而不是存斜率-计数对,map<Integer x,Map<Integer y,Integer cnt>>,因为这样能避免很近的大点问题,比如[0,0], [1000000,10000001],[10000001, 100000002]这种,但实现太麻烦了不做这个优化也行)

 

实现

/**
 * 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 == null) {
            return 0;
        }
        
        Map<Double, Integer> map = new HashMap<>();
        int dup = 0;
        int max = 0;
        for (int i = 0; i < points.length; i++) {
            map.clear();
            dup = 0;
            map.put((double)Integer.MIN_VALUE, 1);
            
            for (int j = i + 1; j< points.length; j++) {
                // 1. duplicate point
                if (points[i].x == points[j].x && points[i].y == points[j].y) {
                    dup++;
                    continue;
                }
                
                double slope;
                if (points[i].x == points[j].x) {
                    slope = (double)Integer.MAX_VALUE;
                } else if (points[i].y == points[j].y) {
                    slope = 0.0;
                } else {
                    slope = (double)(points[i].y - points[j].y) / (double)(points[i].x - points[j].x);
                }
                
                if (map.containsKey(slope)) {
                    map.put(slope, map.get(slope) + 1);
                } else {
                    map.put(slope, 2);
                }
            }
            for (int cnt : map.values()) {
                max = Math.max(max, cnt + dup);
            }
        }
        
        return max;
    }
}

 

 

 

posted @ 2017-11-12 14:56  jasminemzy  阅读(129)  评论(0编辑  收藏  举报