leetcode max-points-on-a-line

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 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.

思路:注意垂直和重叠的点 

 

代码 时间341ms 空间19988k

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
import java.util.*;

public class Solution {
    public int maxPoints(Point[] points) {
        int n = points.length;
        if (n <= 2)
            return n;
        
        int res = 0;
        for (int i=0;i<n;i++){
            HashMap<Float, Integer> a = new HashMap<>();
            int vrt = 0;
            int dup = 1;
            int max = 0;
            for (int j=0;j<n;j++){
                if (i==j)
                    continue;
                if (points[i].x == points[j].x){
                    if (points[i].y == points[j].y){
                        dup++;
                    }
                    else {
                        vrt++;
                    }
                }
                else {
                    float grad = (float)(points[j].y-points[i].y)/(points[j].x-points[i].x);
                    if (a.get(grad) == null)
                        a.put(grad, 1);
                    else {
                        a.put(grad, a.get(grad) + 1);
                    }
                }
                
                int tmp = vrt;
                for (float k:a.keySet())
                    tmp = Math.max(tmp, a.get(k));
                
                max = tmp + dup;
            }
            res = Math.max(res, max);
        }
        return res;
    }
}

  

以上是关于leetcode max-points-on-a-line的主要内容,如果未能解决你的问题,请参考以下文章

如何做LeetCode

leetcode可以写在简历上吗

[Leetcode]leetcode1-10题随记

leetcode分类刷题(续2)

leetcode分类刷题

LintCode,hihoCoder,LeetCode有啥区别