Max Points on a Line

Max Points on a Line

  Total Accepted: 3457  Total Submissions: 35085 My Submissions

 

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

 

http://oj.leetcode.com/problems/max-points-on-a-line/


分别以每个点为原点,计算以该点为原点时,最多有多少个点在同一条线上,只需要计算和该点的斜率,然后用一个 hashmap<slope,count> 存即可。

要特别特别注意的是同一个点出现多次,比如

Point[] = {(0,0) , (1,1), (0,0) }

这里,(0,0) 出现了两次,那么处理的时候,如果和原点是同一个点,不用计算,而是维护一个 counter 来保存有多少个相同点。最后在计算max的时候,要加上相同点,因为相同点可以作为任意一条斜率上的点。



/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    public int maxPoints(Point[] points) {
        if (points.length == 0) return 0;
        Map<Double, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0; i < points.length; i++) {
            int sameCount = 0;
            for (int j = i + 1; j < points.length; j++) {
                double slope = 0.0;
                if (points[i].x == points[j].x && points[i].y == points[j].y) {
                    sameCount++;
                    continue;
                }
                if (points[i].x == points[j].x) slope = Double.MAX_VALUE;
                else if (points[i].y == points[j].y) slope = 0;
                else slope = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x);
                if (!map.containsKey(slope)) map.put(slope, 1);
                else map.put(slope, map.get(slope) + 1);
            }
            if (map.isEmpty()) {
                if (sameCount > max) max = sameCount;
            } else {
                for (Integer n : map.values()) {
                    if (n + sameCount > max) max = n + sameCount;
                }
            }
            map.clear();
        }
        return max + 1;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值