Max Points on a Line(LeetCode)

思路:

  1. 首先排除只有0、1、2个点得情况,直接return points.length(后面讨论的都是大于等于三个点的情况)
  2. 其次,排除掉所有的点为同一点的情况(因为后面需要找出相异点对)
  3. 从前往后遍历,找出一个相异点对(points[i], points[j]),即points[i]不能和points[j]重合
    • 如果两个点坐标相同,则无法确定一条直线,所以要相异点对
    • 令count=2,因为已经至少有points[i]和points[j]两个点了
  4. 从头到尾遍历点points[t],检查points[t]和(points[i], points[j])是否在一条直线上
    • 需要排除t=i和t=j的情况
    • 是在一条直线的话,count++
    • 重复4,直到遍历所有的点
  5. 如果count>max, 令max=count
    • 重复3,直到遍历所有相异点对


代码:

/**
 * 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 i,j,t;
        int max=2;
        i=0;
        while (i<points.length-1 && points[i].x==points[i+1].x && points[i].y==points[i+1].y) i++;//The case that all elements are the same
        if (i==points.length-1) return points.length;
        for (i = 0; i < points.length-1; i++){
            for (j = i+1; j < points.length; j++){
                int count=2;
                if (points[i].x==points[j].x && points[i].y==points[j].y){//point i and point j are the same.
                    continue;
                }
                for (t = 0; t < points.length; t++){
                    if (t==i||t==j) continue;
                    if (checkLine(points[i], points[j], points[t])) count++;
                }
                if (max<count) max=count;
            }
        }
        return max;
    }
    
    static boolean checkLine(Point p1, Point p2, Point p3){
        if ((p3.y-p1.y)*(p2.x-p1.x)==(p2.y-p1.y)*(p3.x-p1.x)) return true;
        else return false;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值