149 Max Points on a Line
来源:互联网 发布:独孤九剑 知乎 编辑:程序博客网 时间:2024/05/06 04:51
做这道题是看到一亩三分地的面经,PhD找Uber SE 暑期实习,卧槽面了两道hard和一道系统设计,果然要求不一样,估计工资也不同吧。。。
此题为hard:1是因为解法不明显,2找到解法后还有些细节要处理,具体见代码。一开始是没有思路的,参考了code ganker大神的代码,重新实现一遍,也改了一个小瑕疵,就是加了 (long),不加的话leetcode上最后3个test case跑不过,于是我自己光凭眼睛debug出来的,hiahia (得意的笑)
思路:找到两个不同的点为基准,然后扫一遍其他所有点,一共3个forloop,复杂度N立方
开始之前,要做一个重要check,就是是否所有点都一样,因为上面的算法检测不出来,另写一个方法来检测
/** * 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) { int len=points.length; if(len==0) return 0; if(samePoints(points)) return len; int max=0; for(int i=0; i<len; i++){ for(int j=i+1; j<len; j++){ if(points[i].x==points[j].x && points[i].y==points[j].y) continue; // 只要相同的点就都pass,因为之后的判断条件对两个相同点是否跟另一个点同斜率的话,就肯定是同斜率啊 //接下来是只有但两个[i],[j]两个点不相同时,才使用下方的斜率判断公式,此判断条件才有效 int num=2; // 因为有[i],[j]两个不同的点作为基准了 for(int k=0; k<len; k++){ if( (k!=i)&& (k!=j) && (long)(points[i].x-points[k].x)*(long)(points[j].y-points[k].y) == (long)(points[j].x-points[k].x)*(long)(points[i].y-points[k].y) ) num++; } // 以上几个long加上去,是因为测试时总有最后两个test case 通不过,检查了判断公式是没问题的,所以就怀疑都是比较大的数相乘越界了。 max=Math.max(max, num); } } return max; } private boolean samePoints(Point[] points){ for(int i=1; i<points.length; i++){ if(points[i].x!=points[0].x || points[i].y!=points[0].y) return false; } return true; }}
0 0
- LeetCode(149)Max Points on a Line
- LeetCode: Max Points on a Line [149]
- 149Max Points on a Line
- LeetCode # 149 Max Points on a Line
- leetcode 149: Max Points on a Line
- LeeCode(149) Max Points on a Line
- 149、Max Points on a Line (Hard)
- Leetcode 149 Max Points on a Line
- LeetCode 149 Max Points on a Line
- 149 Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points On a Line
- Max Points on a Line
- 【Python】健壮的爬虫
- Rxjava参考文档
- 加班与效率
- JS获取IP、IP所在城市、域名、完整URL、当前时间
- Vue生命周期解析
- 149 Max Points on a Line
- 修改MyEclipse中servlet模板
- 【Java】访问控制符
- Django_book(13输出非html内容)
- SparkStreaming如何优雅的停止服务
- linux java 服务调试命令
- 组合数模板
- 洛谷 P1427 小鱼的数字游戏
- 编程语言中运算符的运算效率