題目描述
對於給定的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;
}
}