leetcode3题解 Max Points on a line

题目大意:给出任意点(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; }
 * }
 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值