您的位置:首页 > 其它

Max Points on a Line

2014-01-27 06:02 447 查看


Max Points on a Line

 Total Accepted: 3457 Total Submissions: 35085My
Submissions

 

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

 

http://oj.leetcode.com/problems/max-points-on-a-line/

分别以每个点为原点,计算以该点为原点时,最多有多少个点在同一条线上,只需要计算和该点的斜率,然后用一个 hashmap<slope,count> 存即可。

要特别特别注意的是同一个点出现多次,比如

Point[] = {(0,0) , (1,1), (0,0) }

这里,(0,0) 出现了两次,那么处理的时候,如果和原点是同一个点,不用计算,而是维护一个 counter 来保存有多少个相同点。最后在计算max的时候,要加上相同点,因为相同点可以作为任意一条斜率上的点。

/**
* 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) return 0;
Map<Double, Integer> map = new HashMap<>();
int max = 0;
for (int i = 0; i < points.length; i++) {
int sameCount = 0;
for (int j = i + 1; j < points.length; j++) {
double slope = 0.0;
if (points[i].x == points[j].x && points[i].y == points[j].y) {
sameCount++;
continue;
}
if (points[i].x == points[j].x) slope = Double.MAX_VALUE;
else if (points[i].y == points[j].y) slope = 0;
else slope = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x);
if (!map.containsKey(slope)) map.put(slope, 1);
else map.put(slope, map.get(slope) + 1);
}
if (map.isEmpty()) {
if (sameCount > max) max = sameCount;
} else {
for (Integer n : map.values()) {
if (n + sameCount > max) max = n + sameCount;
}
}
map.clear();
}
return max + 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode