您的位置:首页 > 其它

[leetCode]:Max Points on a Line

2014-04-23 15:16 441 查看
语言 :JAVA

思路 :1、多点能组成一条直线,则必有基于某起始点,其他点相应的斜率相等。

2、为了避免计算斜率出现的精度问题,采用最大公约数,若a/b = c/d,则必有a/b = e*g/f*g,如此当算出c、d的公约数g后,即可简化右侧等式。所有在一条直线上的 点都会具有相同的e,f值。以e,f为键,值则存储在这条线上的点的数量。

3、注意到例如e,g为(1,-2),(-1,2)是两条不同的线,因此为了加以区别,在gcd()中,保留x轴的数值符号。

代码:

/**
* 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 {

int gcd(int a, int b) {
return a==0 ? b : a/Math.abs(a) * Math.abs(gcd(b%a, a));
}

public int maxPoints(Point[] points) {
int result = 0;
for (int i=0; i<points.length; i++) {
HashMap<String, Integer> count = new HashMap<String, Integer>();
int same = 1;
int mx = 0;
int newValue;
for (int j=i+1; j<points.length; j++) {
int x = points[i].x - points[j].x;
int y = points[i].y - points[j].y;
int g = gcd(x, y);
if (g == 0) {
same++;
continue;
}
x /= g;
y /= g;
String keyString = x + " " + y;
if (count.containsKey(keyString)) {
newValue = count.get(keyString) + 1;
} else {
newValue = 1;
}
count.put(keyString, newValue);
mx = Math.max(mx, newValue);
}
result = Math.max(result, mx+same);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: