leetcode--max-points-on-a-line

来源:互联网 发布:无法无天小说吾知 编辑:程序博客网 时间:2024/06/06 11:46

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:2点确定一条直线,在这个过程中,需要注意和第一个重复的点,这个点只能看成一个




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

public class Solution {    public int maxPoints(Point[] points) {        int len=points.length;        if(len<=2)return len;        int maxNum=2;        int x1=0,x2=0,y1=0,y2=0;        for(int i=0;i<len;i++){            int num=0;//记录每个和第一个点重复的点                        for(int j=i+1;j<len;j++){                int temp=1;                x1=points[j].x-points[i].x;                y1=points[j].y-points[i].y;                if(x1==0&&y1==0){                    num++;                }else{                    temp++;                    for(int k=j+1;k<len;k++){                        x2=points[k].x-points[j].x;                        y2=points[k].y-points[j].y;                        if(x1*y2==y1*x2){                            temp++;                        }                    }                }                if(maxNum<temp+num){                    maxNum=temp+num;                }            }        }        return maxNum;    }}

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