第(3)题 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.
大意就是给定的n个点在二维平面上,求在同意条直线上的点最多有几个。
思路:两点可以确定一条直线,用斜率来判断第三个点是否在同一条直线上。用穷举法依次遍历每一个点。
利用横纵坐标差来判断斜率。
代码如下:
/**
* 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 max = 2;
int tmp = 0;
int num = 1;
for(int i = 0; i < points.length; i++){
num = 1;
tmp = 0;
for(int j = i + 1; j < points.length; j++){
int deletex = points[i].x - points[j].x;
int deletey = points[i].y - points[j].y;
if(deletex==0&&deletey==0){//两个点重合
tmp++;
continue;
}
num++;
for(int k = j + 1; k < points.length; k++){
int tmpdeletex = points[i].x - points[k].x;
int tmpdeletey = points[i].y - points[k].y;
if(tmpdeletex*deletey == tmpdeletey*deletex){
num++;
}
}
if(max < num + tmp){
max = num + tmp;
}
num = 1;
}
if(max < num + tmp){
max = num + tmp;
}
}
return max;
}
}