149. Max Points on a Line

44 篇文章 0 订阅
13 篇文章 0 订阅

Problem:

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.

 

Analysis:

本题直接使用斜率的Map是不能够解决的,会遇到精度问题,需要另外想办法。这时我们可以考虑先将分数进行约分,然后再将其转换成为字符串的形式进行Map,代码如下:

 

Code:

class Solution {
    public int maxPoints(int[][] points) {
        if(points == null) {
            return 0;
        } else if(points.length <= 2) {
            return points.length;
        }
        
        int solution = 0;
        for(int i = 0; i < points.length; i++) {
            
            Map<String, Integer> temp = new HashMap<String, Integer>();
            int dups = 0;
            
            for(int j = i + 1; j < points.length; j++) {
                int x = points[j][0] - points[i][0], y = points[j][1] - points[i][1];
                if(x == 0 && y == 0) {
                    dups++;
                    continue;
                }   
                int gcd = Gcd(x, y);
                x /= gcd;
                y /= gcd;
                String slope = y + "/" + x;
                //System.out.println("[log]: (" + i + ", " + j + ") " + slope);
                temp.put(slope, temp.getOrDefault(slope, 0) + 1);
            }
            
            int linesMax = 0;
            for(int value : temp.values()) {
                linesMax = Math.max(linesMax, value);
            }
            
            solution = Math.max(solution, 1 + linesMax + dups);
        }
        return solution;
    }
    
    private int Gcd(int a, int b) {
        while(b != 0) {
            int temp = b;
            b = a%b;
            a = temp;
        }
        
        return a;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值