您的位置:首页 > 其它

LintCode:最多有多少个点在一条直线上

2015-11-24 23:10 309 查看
给出二维平面上的n个点,求最多有多少点在同一条直线上。
您在真实的面试中是否遇到过这个题?

Yes

样例

给出4个点:
(1, 2)
,
(3,
6)
,
(0, 0)
,
(1,
3)

一条直线上的点最多有3个。

标签 Expand
解题思路:
O(n^2)的时间复杂度,利用2点求斜率,map保存斜率。
需要注意的是2点元素相等和斜率不存在的情况

/**
* 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 {
/**
* @param points an array of point
* @return an integer
*/
public int maxPoints(Point[] points) {
// Write your code here
if (points == null || points.length == 0)
return 0;
HashMap<Double, Integer> map = new HashMap<>();
int res = 1;
for (int i = 0; i < points.length; i++) {
map.clear();
int dup = 0;
map.put((double)Integer.MIN_VALUE, 1);
for (int j = i+1; j < points.length; j++) {
if (points[j].x == points[i].x&&points[j].y == points[i].y) {
dup++;continue;
}
double k;
if (points[j].x - points[i].x == 0) {
k = Integer.MAX_VALUE;
} else {
k = 0.0 + (double)(points[j].y - points[i].y)
/ (double)(points[j].x - points[i].x);
}
if (map.containsKey(k)) {
map.put(k, map.get(k) + 1);
} else {
map.put(k, 2);
}
}
for (int item : map.values()) {
if (item+dup > res) {
res = item+dup;
}
}
}
return res;
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: