Leetcode 149. Max Points on a Line
来源:互联网 发布:php redis 扩展 编辑:程序博客网 时间:2024/03/28 21:03
149. Max Points on a Line
Total Accepted: 56036 Total Submissions: 392865 Difficulty: Hard
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
看着这submission的accept率大概就知道这个题目非常的繁琐。
自己的想法是每一个点i,去跟其后面的所有点比较。两点会有一个斜率,这样用两个map,一个存当前点的x和y直线,另外一个存两点的直线。不断更新,最后输出最大值。
然而:
一到same的点就结果不对。比如[[0,0],[1,1],[0,0]]自动就输出了4。经过各种debug无果,直到看了别人的代码,才发现问题在于:每一个新循环的i值,都必须新建一个map,而不是所有的点共用一个,这样就不会发生1-2, 1-3计算之后2-3又重复加入结果中的的问题(因为1的所有点判断完之后就更新了结果,之后2再判断虽然重新又判断了该直线,但是并不会和上次的结果累计到一起!)。
另一个trick是碰到same的点,same++就行了,什么都不用做,最后赋值比较那里加上该值就行。
代码中有vertical的计数,用来记录无斜率的点的数量;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; } * } */public class Solution { public int maxPoints(Point[] points) { if(points.length<=2) return points.length; int res=0; for (int i=0; i<points.length; i++){ HashMap<Double, Integer> slope = new HashMap<Double, Integer>(); // 一定要新建 int same=0; int vertical=1; int line=0; double sl; for(int j=i+1; j<points.length; j++){ if(points[j].x==points[i].x && points[j].y==points[i].y){ same++; continue; }else if (points[j].x==points[i].x){ vertical++; continue; // no slope }else if (points[j].y==points[i].y){ // 0.0 != -0.0 sl = 0.0; }else{ sl = (double)(points[j].y-points[i].y)/(points[j].x-points[i].x); // 一定要用(double)转换,否则会有个case精度不过 } int num = slope.get(sl) == null ? 2 : slope.get(sl) +1; line = Math.max(line, num); // line记录了所有直线中,最大的数目; vertical是记录垂直x轴的点的数目 slope.put(sl, num); } res = Math.max(res, Math.max(line, vertical)+same); } return res; }}
0 0
- LeetCode 149. Max Points on a Line
- [leetcode] 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- leetcode.149. Max Points on a Line
- LeetCode-149.Max Points on a Line
- leetcode 149. Max Points on a Line
- leetCode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- 【LeetCode】149. Max Points on a Line
- 2016-04-29知识整理
- android里面的USB功能----Host模式
- hdu 1035 Robot Motion
- Quartz2D图片裁剪圆的做法
- 获取List集合中的重复数据和重复次数(适用于有着连续的相同数据项时)
- Leetcode 149. Max Points on a Line
- hdu3294 manacher算法
- Android蓝牙4.0之GATT
- J2EE常见路径处理
- Python 模块学习 logging
- setTextColor设置
- 常用socket函数
- MFC使用mscomm串口通信
- android的跑马灯效果