您的位置:首页 > 其它

Max Points on a Line

2014-01-09 15:08 357 查看
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; }
* }
*/
import java.text.DecimalFormat;
public class Solution {
public int maxPoints(Point[] points) {
Map<Double, Integer> slopeMap  = new HashMap<>();
int max = 0;

int n = points.length;
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
for (int i = 0; i < n; i++) {
int duplicate = 1;
Point p1 = points[i];
slopeMap.clear();
slopeMap.put(Double.MIN_VALUE, 0);
for (int j = i + 1; j < n; j++) {
Point p2 = points[j];
double slope = 0.0;
if (p2.x - p1.x != 0) {
slope = (p2.y - p1.y) * 1.00 / (p2.x - p1.x);
}
else if (p2.y == p1.y) {
duplicate++;
continue;
}
else {
slope = Double.MAX_VALUE;
}
if (slope == -0.0) {
slope = 0.0;
}
if (slopeMap.containsKey(slope)) {
int value = slopeMap.get(slope);
slopeMap.put(slope, value + 1);
}
else{
slopeMap.put(slope, 1);
}
}
for (double key : slopeMap.keySet()) {
int value = slopeMap.get(key);
if (value + duplicate > max) {
max = value + duplicate;
}
}

}
return max;
}
}
这道题值得注意的地方有很多:

1. 重复点要考虑,做之前问问考官有没有重复点;

2. java 中double 有0.0 和-0.0之分,所以要多加一个判断。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: