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.

这道题考虑用如下表达式表达直线:

point:(a0,b0), (a1,b1), 
line:(a1-a0)y+(b0-b1)x+(a0b1-a1b0)=0


麻烦在于:相同点的处理:

先找一个点i,

      再找一个点j,如果i,j相同,则same++,表示当前重复的点

      如果i,j不同,则可确定一条直线,后面的点k带入方程,满足条件tmp++

      最后的一条直线的点的个数就是same+tmp

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
 
 //point:(a0,b0), (a1,b1), 
 //line:(a1-a0)y+(b0-b1)x+(a0b1-a1b0)=0
public class Solution {
    public int maxPoints(Point[] points) {
        int i,j,k;
        int n=points.length;
        if(n<3)
          return n;
        int a,b,c;
        int tmp,max=2;
        int same;
        for(i=0;i<n;i++)
        {
            same=0;
            tmp=1;
            for(j=i+1;j<n;j++)
            {
                a=(points[j].x-points[i].x);
                b=(points[i].y-points[j].y);
                if(a==0 && b==0)
                {
                    tmp++;
                    same++;
                    //all same point
                    if(j==n-1 && tmp>max)
                        max=tmp;
                    continue;
                }
                else
                {
                    c=(points[i].x*points[j].y-points[j].x*points[i].y);
                    tmp++;
                    for(k=j+1;k<n;k++)
                    {
                        if((a*points[k].y+b*points[k].x+c)==0)
                        tmp++;
                    }
                    if(tmp>max)
                        max=tmp;
                    tmp=same+1;
                }
            }
        }
        return max;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值