LeetCode——Max Points on a Line
2017-11-01 15:23
417 查看
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.题目大意:
给出一组点,求在同一条直线上的点的最大数。思路:
首先记录下重合的点的数目,和斜率不存在时,处于同一条直线上的点的数目。之后使用HashMap数据结构来存储和这个点各个斜率上点的个数。统计完成之后将斜率不存在时点的数目设为最大值,以此和斜率存在时的点的数目进行比较。取出最大值(不包括和已知点重合的点的数目)。之后和之前求出的最大值进行一个比较,不要忘记在比较的时候需要在当前求出的最大值上加上重合点的数目。最后返回求出的最大值。解题代码:
import java.util.HashMap; import java.util.Iterator; public class Solution{ public int maxPoints(Point[] points) { int result = 0; int fresult = 0; //数组长度小于2时的处理 if(points.length < 2){ return points.length; } //定义一个哈希表用于存储斜率相同的点的个数 HashMap<Double, Integer>hash = new HashMap<Double,Integer>(); //重合的部分 int rep = 0; //非重合的部分 int dif = 0; //计算重合部分的数量 for(int i=0;i<points.length;i++){ hash.clear(); rep = 1; dif = 0; for(int j=0;j<points.length;j++){ if(points[i].x == points[j].x){ if(i == j){ continue; } if(points[i].y == points[j].y){ rep++; }else{ dif++; } }else{ //收集各个斜率下的个数 double k = ((double)points[j].y - (double)points[i].y)/((double)points[j].x - (double)points[i].x); if(!hash.containsKey(k)){ hash.put(k, 1); }else{ hash.put(k, hash.get(k)+1); } } } result = dif; //遍历哈希表 Iterator<Double>ite = hash.keySet().iterator(); while(ite.hasNext()){ result = Math.max(result, hash.get(ite.next())); } fresult = Math.max(fresult, result+rep); } return fresult; } }
相关文章推荐
- Max Points on a Line(leetcode)
- leetcode-Max Points on a Line
- LeetCode-Max Points on a Line[AC源码]
- 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
- Leetcode229: Max Points on a Line
- 【leetcode】Max Points on a Line
- [Leetcode] 149. Max Points on a Line 解题报告
- Max Points on a Line | leetcode
- [LeetCode] Max Points on a Line
- [Leetcode][JAVA] Max Points on a Line
- LeetCode 149. Max Points on a Line
- LeetCode刷题笔录Max Points on a Line
- [LeetCode]题解(python):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