首页 > 其他 > 详细

Max Points on a Line

时间:2015-10-23 02:06:20      阅读:248      评论:0      收藏:0      [点我收藏+]

Given?n?points on a 2D plane, find the maximum number of points that lie on the same straight line.

?

/**
 * 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 == 0 || points == null) {
			return 0;
		}
		if (points.length == 1) {
			return 1;
		}
		int res = 1;
		for (int i = 0; i < points.length; i++) {
			HashMap<Float,Integer> hashMap = new HashMap<Float, Integer>();
			int same = 0;
			int max = 1;
			for (int j = 0; j < points.length; j++) {
				if (i == j) {
					continue;
				}
				if (points[i].x == points[j].x && points[i].y == points[j].y) {
					same++;
					continue;
				}
				float tmp = (float)(points[i].y - points[j].y) / (points[i].x - points[j].x);
				if (hashMap.containsKey(tmp)) {
					hashMap.put(tmp, hashMap.get(tmp) + 1);
				} else {
					hashMap.put(tmp, 2);
				}
			}
			for (Integer value : hashMap.values()) {
				max = Math.max(max, value);
			}
			max += same;
			res = Math.max(max, res);
		}
		return res;
	}
}

?

Max Points on a Line

原文:http://hcx2013.iteye.com/blog/2251153

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!