leetCode--max-points-on-a-line

題目描述

對於給定的n個位於同一二維平面上的點,求最多能有多少個點位於同一直線上

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


解題思路:主要是運用了三點共線原理。

      先確定兩個點可以構成一條線段,運用三點共線原理來判斷第三個點是否與確定的兩個點共線。

 



  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==null)return 0;
        if(points.length<3)return points.length;
        int n=points.length;
        int res=0;
        
        for(int i=1;i<n;i++){
            int count=0;
            int x=points[i].x;
            int y=points[i].y;
            int dx=points[i-1].x-x;
            int dy=points[i-1].y-y;
            if(dx==0&&dy==0){
                for(int j=0;j<n;j++){
                    if(points[j].x==x&&points[j].y==y){
                        count++;
                    }
                }
            }else{
                for(int j=0;j<n;j++){
                    if((points[j].x-x)*dy==(points[j].y-y)*dx){
                        count++;
                    }
                }
            }
            res=res>count?res:count;
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章