zoukankan      html  css  js  c++  java
  • [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);
        }
    }
  • 相关阅读:
    PHP观察者模式 (转)
    PHP单例模式 (转)
    PHP解决并发问题的几种实现(转)
    php结合redis实现高并发下的抢购、秒杀功能 (转)
    使用 redis 减少 秒杀库存 超卖思路 (转)
    mysql视图学习总结(转)
    mysql 存储过程
    PHP中的魔术方法和关键字
    bzoj3462DZY Loves Math II
    bzoj1453[Wc]Dface双面棋盘
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12181847.html
Copyright © 2011-2022 走看看