• 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;
        }
    }
     
  • 相关阅读:
    sublime text3快捷键
    SublimeText3追踪函数工具CTags设置及使用
    mysql的表锁
    ESXI vSphere如何设置虚拟机开机自启动
    gitee支持的开源许可证
    keepalive安装部署踩坑参考
    《牧神记》中诗词大全,有的可能是作者瞎编的
    定位Linux服务器SSH敲命令响应慢的问题
    Crypto-JS——Uncaught Error: Malformed UTF-8 data
    VUE——vue中组件之间的通信方式有哪些
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7821650.html
Copyright © 2020-2023  润新知