[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 };
相关文章推荐
- JavaScript高级程序设计笔记(4)
- 《Javascript 高级程序设计》-第4章:知识总结
- Knockoutjs快速入门(经典)
- js1
- Knockoutjs的环境搭建教程
- 面向对象编程js
- js 数组去重
- 用JavaScript语言编写:点击对应颜色的小方块更换主题颜色
- Javascript中自执行函数
- 用javascript设置图片的轮播
- 几种自动执行js代码的方式
- HTML/CSS/Javascript调试入门(转)
- [LeetCode][JavaScript]Subsets II
- HTML/CSS/JavaScript学习总结(转)
- [LeetCode][JavaScript]Subsets
- JavaScript基础学习之-JavaScript权威指南--3.2文本
- javascript实现简单日期下拉选择器
- JS学习十六天----单例模式
- JavaScript基础学习之-JavaScript权威指南--3.1数字
- Top 10:HTML5、JavaScript 3D游戏引擎和框架