lintcode,最多有多少个点在一条直线上

给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
给出4个点:(1, 2), (3, 6), (0, 0), (1, 3)。
一条直线上的点最多有3个。

解题思路:从第一个点开始遍历,每次和其他所有点对比,判断是否是重合点,以及是否是同一x值的点,map用来保存斜率,然后判断斜率是否存在,每次更新max。
一刷没ac

/**
 * 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 {
    /**
     * @param points an array of point
     * @return an integer
     */
    public int maxPoints(Point[] points) {
        if(points == null || points.length == 0) return 0;
        if(points.length <= 2) return points.length;
        int result = 0;
        for(int i = 0; i < points.length; i++){
            int pointx = points[i].x;
            int pointy = points[i].y;
            HashMap<Double, Integer> map = new HashMap<Double, Integer>();
            int samep = 0;
            int samex = 1;
            for(int j = 0; j < points.length; j++){
                if(j != i){
                    if(points[j].x == points[i].x && points[j].y == points[i].y) samep++;
                    if(points[j].x == points[i].x){
                        samex++;
                        continue;
                    }
                    double k = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
                    if(map.containsKey(k)) map.put(k,map.get(k)+1);
                    else map.put(k,2);
                    result = Math.max(result, map.get(k)+samep);
                }
            }
            result = Math.max(result, samex);
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值