【leetcode】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.

解法:从任意一点开始,找斜率相同的最大点数,用HashMap

代码:

/**
	 * 从任意一点开始,找斜率相同的最大点数
	 * 特别注意和开始点重点的情况
	 * @param points
	 * @return
	 */
	public int maxPoints(Point[] points){
		HashMap<Float, Integer> slopeMap = new HashMap<Float, Integer>();
		int size = points.length;
		if(size == 0 || size == 1)
		    return size;
		int maxSlopeTime = 1;
		for(int i = 0; i < size; i++){
			slopeMap.clear();
			int tempMaxSlopeTime = 0;;
			int duplicate = 1;//表示和第i个点重复的次数
			for(int j = i + 1; j < size; j++){
				if(points[i].x == points[j].x && points[i].y == points[j].y){
					duplicate++;
					continue;
				}
				float dx = points[i].x - points[j].x;
				float dy = points[i].y - points[j].y;
				float slope;
				if(dx == 0.0f)
					slope = 0.0f;//如果直接用dy/dx,则会有-0.0和0.0两种情况
				else if(dy == 0.0f)
					slope = Float.POSITIVE_INFINITY;//如果直接用dy/dx,则会有-infinity和infinity两种情况
				else
					slope = dy/dx;
				if(slopeMap.containsKey(slope)){
					slopeMap.put(slope, slopeMap.get(slope) + 1);
					if(tempMaxSlopeTime < slopeMap.get(slope))
						tempMaxSlopeTime = slopeMap.get(slope);
				}
				else{
					slopeMap.put(slope, 1);
					if(tempMaxSlopeTime < 1)
						tempMaxSlopeTime = 1;
				}
			}
			if(tempMaxSlopeTime + duplicate > maxSlopeTime)
				maxSlopeTime = tempMaxSlopeTime + duplicate;
		}
		return maxSlopeTime;
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值