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);
        }
    }
  • 相关阅读:
    Why use strong named assemblies?
    Dependency Walker
    “等一下,我碰!”——常见的2D碰撞检测
    MOBA游戏的网络同步技术
    VS2017如何配置openGL环境
    UE4关于Oculus Rift (VR)开发忠告
    UE4 的json读写方式
    Blueprint 编译概述
    UE4编码规范
    Unreal Enginer4特性介绍
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12181847.html
Copyright © 2011-2022 走看看