【leetcode】Max Points on a Line
来源:互联网 发布:网络大神级作家排行榜 编辑:程序博客网 时间:2024/04/30 14:36
题目:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
解法:从任意一点开始,找斜率相同的最大点数,用HashMap
代码:
/** * 从任意一点开始,找斜率相同的最大点数 * 特别注意和开始点重点的情况 * @param points * @return */public int maxPoints(Point[] points){HashMap<Float, Integer> slopeMap = new HashMap<Float, Integer>();int size = points.length;if(size == 0 || size == 1) return size;int maxSlopeTime = 1;for(int i = 0; i < size; i++){slopeMap.clear();int tempMaxSlopeTime = 0;;int duplicate = 1;//表示和第i个点重复的次数for(int j = i + 1; j < size; j++){if(points[i].x == points[j].x && points[i].y == points[j].y){duplicate++;continue;}float dx = points[i].x - points[j].x;float dy = points[i].y - points[j].y;float slope;if(dx == 0.0f)slope = 0.0f;//如果直接用dy/dx,则会有-0.0和0.0两种情况else if(dy == 0.0f)slope = Float.POSITIVE_INFINITY;//如果直接用dy/dx,则会有-infinity和infinity两种情况elseslope = dy/dx;if(slopeMap.containsKey(slope)){slopeMap.put(slope, slopeMap.get(slope) + 1);if(tempMaxSlopeTime < slopeMap.get(slope))tempMaxSlopeTime = slopeMap.get(slope);}else{slopeMap.put(slope, 1);if(tempMaxSlopeTime < 1)tempMaxSlopeTime = 1;}}if(tempMaxSlopeTime + duplicate > maxSlopeTime)maxSlopeTime = tempMaxSlopeTime + duplicate;}return maxSlopeTime;}
0 0
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- Leetcode: Max Points on a Line
- LeetCode - Max Points on a Line
- LeetCode 之 Max Points on a Line
- LeetCode | Max Points on a Line
- [LeetCode] Max Points on a Line
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- leetcode:【Max Points on a Line】
- Max Points on a Line - LeetCode
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- leetcode - Max Points on a Line
- LeetCode(149)Max Points on a Line
- OpenWRT数据发送过程【Linux内核-OpenWRT】
- 如果获取java应用的加载的classpath
- 8个游戏开发工具让你不懂编程也能做游戏
- iOS 显示内存空间
- ASCII 码排序
- 【leetcode】Max Points on a Line
- C/C++ 中fopen_s与fopen
- C++读写文件
- C++ static关键字详解
- coco2d-x CCScrollView实现背包翻页,仅供参考
- 开启远程端口
- [hdu-2046] 骨牌铺方格
- 再读《Short Brain 》
- 最受欢迎的ASP.NET的CMS下载