149. Max Points on a Line

原文链接:https://leetcode.com/problems/max-points-on-a-line/?tab=Description

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

要求:求出平面n个点中,最多共线的点数。

方法:选定一个点,计算其他点与它的斜率,如果斜率不存在则记为最大值;如果相同点,则设置一个标志计数+1,在每轮计算后更新最大值。在选定新点后将重复标志、map初始化。

/** 
 * 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 < 3) return points.length;  
          
        int max = 0;//用于返回的结果,即共线点的最大个数  
        Map<Double, Integer> map = new HashMap<Double, Integer>();//保存同一个斜率的点的个数  
          
        for (int i = 0; i < points.length; i++) {//以每一个点为固定点  
            map.clear();  
            int duplicate = 1;//记录跟固定点重合的个数  
              
            for(int j = 0 ; j < points.length; j++){//遍历其他点,求其与固定点之间的斜率  
                if (i == j) continue;//如果是自己,跳过  
                double slope = 0.0;//斜率  
                  
                if (points[i].x == points[j].x && points[i].y == points[j].y) {//如果跟固定点重合  
                    duplicate++;  
                    continue;  
                } else if (points[i].x == points[j].x) {//如果跟固定点在同一条竖线上,斜率设为最大值  
                    slope = Integer.MAX_VALUE;  
                } else {//计算该点与固定点的斜率  
                    slope = 1.0 * (points[i].y - points[j].y) / (points[i].x - points[j].x);  
                }  
                map.put(slope, map.containsKey(slope) ? map.get(slope) + 1 : 1);  
            }  
              
            //更新最优解  
            if (map.keySet().size() == 0) {//如果map为空  
                max = duplicate > max ? duplicate : max;  
            } else {  
                for (double key : map.keySet()) {  
                    max = Math.max((duplicate + map.get(key)), max);   
                }  
            }  
        }  
        return max;  
    }  
} 
注意在计算斜率时,需要乘1.0,以进行数值的类型转换;

dulplicate初始值为1,map需要清空

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值