您的位置:首页 > 其它

leetcode3题解 Max Points on a line

2014-07-30 20:36 411 查看
题目大意:给出任意点(x,y)的数组,找出在同一条线上最多的点数

解题思路:直接暴力解法,三重循环,任意连接两条线,通过斜率判断其他点是否在上面

使用一个布尔变量isAllSame来判断所有的点是否一样,连接不同的两个点形成一条线,对第三个点,考虑(1)这条线如果垂直,只考虑x是否相等 (2)这条线不垂直,考虑a)是否和其他两个点一样 b)斜率是否相等

更新最大值maxCount

注意点:重复的点计算,斜率计算分母为0的情况需要特殊考虑

public class Solution {

public static void main(String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(1,1);
Point p3 = new Point(2,3);
Solution s = new Solution();
Point[] points = new Point[]{p1, p2, p3};
System.out.println(s.maxPoints(points));

}
public boolean isPointEqual(Point p1, Point p2){ //判断两个点是否相等
if(p1.x == p2.x && p1.y == p2.y){
return true;
}
return false;
}
public int maxPoints(Point[] points){
if(points.length <= 2) return points.length;
int maxCount = Integer.MIN_VALUE;
boolean isAllSame = false;
for(int i = 0; i < points.length; i++){
for(int j = i+1; j < points.length; j++){
if(!(points[i].x == points[j].x && points[i].y == points[j].y)){
isAllSame = true;
double ratio = Double.MAX_VALUE;
int pointCount = 2;
boolean isVertical = false;
if(points[i].x == points[j].x){
isVertical = true;
}else{
ratio = (double)(points[j].y - points[i].y)/(points[j].x - points[i].x);
}
for(int k = 0; k < points.length; k++){
if(k != i && k != j){
if(isVertical){
if(points[k].x == points[i].x){ //连线垂直,只考虑x
pointCount++;
}
}else{ //分别考虑点是否和其他两个点相等、斜率
if(this.isPointEqual(points[k], points[i])||this.isPointEqual(points[k], points[j])){
pointCount++;
}else{
double tmp = (double)(points[k].y - points[i].y)/(points[k].x - points[i].x);
if(ratio == tmp){
pointCount++;
}
}
}
}
}
if(pointCount > maxCount){
maxCount = pointCount;
}
}
}
}
if(!isAllSame){
return points.length;
}else{
return maxCount;
}
}
}
/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: