149. Max Points on a Line
来源:互联网 发布:windows系统安装工具 编辑:程序博客网 时间:2024/05/29 09:24
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
不愧是hard
一开始考虑的是 只要y/x的值相等,就在一条直线上,但是对于(1,2),(1,3)呢,也是在一条直线上的
想一下直线的表达式: y=ax+b
public int maxPoints(Point[] points) { if (points==null) return 0; if (points.length<=2) return points.length; Map<Integer,Map<Integer,Integer>> map = new HashMap<Integer,Map<Integer,Integer>>(); int result=0; for (int i=0;i<points.length;i++){ map.clear(); int overlap=0,max=0; for (int j=i+1;j<points.length;j++){ int x=points[j].x-points[i].x; int y=points[j].y-points[i].y; if (x==0&&y==0){ overlap++; continue; } int gcd=generateGCD(x,y);//求最大公约数 if (gcd!=0){ x/=gcd; y/=gcd; } //x,y分别除以gcd 之后就以x,y来代表斜率 //实际上用x/y来代表斜率也可以 但是会比较麻烦 1.需要用double表示 2.y等于0需要特殊处理 if (map.containsKey(x)){ if (map.get(x).containsKey(y)){ map.get(x).put(y, map.get(x).get(y)+1); }else{ map.get(x).put(y, 1); } }else{ Map<Integer,Integer> m = new HashMap<Integer,Integer>(); m.put(y, 1); map.put(x, m); } max=Math.max(max, map.get(x).get(y)); } result=Math.max(result, max+overlap+1); } return result; }private int generateGCD(int a,int b){ if (b==0) return a; else return generateGCD(b,a%b);}
一篇讲辗转相除法很好的文章:
http://www.ailab.cn/view/2016101913850.html
阅读全文
0 0
- LeetCode 149. Max Points on a Line
- 149.Max Points on a Line
- 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
- 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
- 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- leetCode 149. Max Points on a Line
- 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- php json_encode值中大括号与花括号区别
- 用了18年,科沃斯将扫地机器人从工具升级到管家
- 360私有化一波三折!细数那些回归受阻的中概股!
- logistic函数
- Linux常用命令之tar
- 149. Max Points on a Line
- LINUX输入子系统
- 一个项目
- 【OpenCV入门教程之十二】OpenCV边缘检测:Canny算子,Sobel算子,Laplace算子,Scharr滤波器合辑
- ThreadPoolExecutor
- JS 日期的获取和计算 ios不兼容问题
- 2017.10.28 排序 思考记录
- HDU-1710 给出前序中序输出后序
- css揭秘-2