【leetcode】Max Points on a Line
2014-04-29 20:23
447 查看
题目:Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
解法:从任意一点开始,找斜率相同的最大点数,用HashMap
代码:
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两种情况 else slope = 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; }
相关文章推荐
- 【leetcode】Max Points on a Line (python)
- Leetcode: Max Points on a Line
- Leetcode-Max Points on a Line
- LeetCode---3.Max Points on a Line
- [LeetCode] Max Points on a Line
- leetcode 刷题之路 3 Max Points on a Line
- [leetcode]Max Points on a Line @ Python
- [Leetcode]Max Points on a Line
- 【LeetCode with Python】 Max Points on a Line
- Leetcode229: Max Points on a Line
- [LeetCode]149. 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 149. Max Points on a Line
- (leetcode)Max Points on a Line
- LeetCode149—Max Points on a Line
- LeetCode-Max Points on a Line