您的位置:首页 > 其它

Max Points on a Line(LeetCode)

2014-07-18 17:39 246 查看
思路:

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

从头到尾遍历点points[t],检查points[t]和(points[i], points[j])是否在一条直线上
需要排除t=i和t=j的情况
是在一条直线的话,count++
重复4,直到遍历所有的点

如果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;
    }
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode