• [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);
        }
    }
  • 相关阅读:
    mysql 存储引擎
    mysql优化的理解(转载)
    转载:字节流与字符流的理解
    转载:java面试题(二)
    androidstudio与unity进行交互
    偶尔出现button不能点击的情况
    R文件报错:cannot resolve symbol ‘R’
    有时候老师报空错误,但是输出和在面板上看是得到了实例的
    边缘与多边形碰撞盒不能编辑的原因
    编程内功修炼
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12181847.html
Copyright © 2020-2023  润新知