您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Max Points on a Line

2015-08-15 23:55 661 查看

Max Points on a Line

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

求有多少点在一直线上。

粗暴地用二重循环遍历。

每一轮都构造一个哈希表,用来记录斜率,斜率k = (y1 - y2) / (x1 - x2)。

注意到特殊情况:

1.两点重合,用countSamePoint记下重复的点,最后加到结果上。

2.两点与X轴平行,此时y1 - y2 = 0, k = 0,构造哈希表,提前塞一个slopeMap[0] = 0。

3.两点与Y轴平行,此时x1 - x2 = 0, k = Infinity,同上塞一个slopeMap[Infinity] = 0。

/**
* Definition for a point.
* function Point(x, y) {
*     this.x = x;
*     this.x = y;
* }
*/
/**
* @param {Point[]} points
* @return {number}
*/
var maxPoints = function(points) {
if(points.length <= 1){
return points.length;
}
var res = -1, countSamePoint, max, i, j, slopeMap, curr, slope, tmp;
for(i = 0; i < points.length; i++){
curr = points[i];
max = 0;
countSamePoint = 1;
slopeMap = {};
slopeMap[0] = 0; slopeMap[Infinity] = 0;
for(j = 0; j < points.length; j++){
if(i === j){
continue;
}
if(points[j].x === curr.x && points[j].y === curr.y){
countSamePoint++;
}else{
slope = (points[j].y - curr.y) / (points[j].x - curr.x);
if(slopeMap[slope] === undefined){
slopeMap[slope] = 1;
}else{
slopeMap[slope]++;
}
tmp = slopeMap[slope];
if(tmp > max){
max = tmp;
}
}
if(max + countSamePoint > res){
res = max + countSamePoint;
}
}
}
return res;
};


Test Cases:

function test(){
console.log(maxPoints([])); //0
console.log(maxPoints([new Point(0,0)])); //1
console.log(maxPoints([new Point(0,0),new Point(0,0)])); //2
console.log(maxPoints([new Point(1,1),new Point(2,1)])); //2
console.log(maxPoints([new Point(1,1),new Point(1,2)])); //2
console.log(maxPoints([new Point(0,0),new Point(1,1),new Point(0,0)])); //3
console.log(maxPoints([new Point(1,1),new Point(2,2),new Point(2,3),new Point(3,3),new Point(5,10)]));  //3
console.log(maxPoints([new Point(1,1),new Point(1,1),new Point(2,2),new Point(2,2)])); //4

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