LeetCode刷题笔录Max Points on a Line
2014-11-07 04:45
357 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
两个点是必然共线的。三个点共线的条件是任意两点间的斜率相等。那么解法来了:对于每一个点遍历剩下的所有点并计算斜率,用一个hashmap来记录同一个slope出现的次数,这些点就是共线的点。
注意两点:
1.给的点集中可能有重复的点,两个重复的点与任何斜率都共线,因此要单独考虑identical points的情况
2.斜率可以是正无穷
on a 2D plane, find the maximum number of points that lie on the same straight line.
两个点是必然共线的。三个点共线的条件是任意两点间的斜率相等。那么解法来了:对于每一个点遍历剩下的所有点并计算斜率,用一个hashmap来记录同一个slope出现的次数,这些点就是共线的点。
注意两点:
1.给的点集中可能有重复的点,两个重复的点与任何斜率都共线,因此要单独考虑identical points的情况
2.斜率可以是正无穷
/** * 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) { Map<Float, Integer> slopeMap = new HashMap<Float, Integer>(); if(points == null || points.length == 0) return 0; int max = 0; for(int i = 0; i < points.length; i++){ slopeMap.clear(); //to store potential identical duplicate points int identicals = 1; for(int j = 0; j < points.length; j++){ if(i == j) continue; int x1 = points[i].x; int y1 = points[i].y; int x2 = points[j].x; int y2 = points[j].y; //if the two points are identical if(x1 == x2 && y1 == y2){ identicals++; continue; } Float slope = (x2 - x1 == 0) ? Float.MAX_VALUE : ((float)(y2 - y1) / (x2 - x1)); if(slopeMap.containsKey(slope)){ int prevCount = slopeMap.get(slope); slopeMap.put(slope, prevCount + 1); } else slopeMap.put(slope, 1); } if(slopeMap.isEmpty()){ max = Math.max(max, identicals); } for(Map.Entry<Float, Integer> entry : slopeMap.entrySet()){ max = Math.max(max, entry.getValue() + identicals); } } return max; } }
相关文章推荐
- Leetcode-max-points-on-a-line
- 【leetcode】Max Points on a Line (python)
- LeetCode Max Points on a Line
- 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----Max Points On a Line
- [Leetcode][python]Max Points on a Line
- [leetcode]Max Points on a Line @ Python
- LeetCode: Max Points on a Line
- leetcode-[3]Max Points on a Line
- leetcode---max-points-on-a-line---穷举
- LeetCode-Max Points on a Line-最大共线的点的数目-Hash
- 【leetcode】Max Points on a Line
- [LeetCode][JavaScript]Max Points on a Line
- LeetCode | Max Points on a Line
- Leetcode 149. Max Points on a Line
- LeetCode - Max Points on a Line
- 【leetcode每日一题】149.Max Points on a line