LeetCode—max-points-on-a-line(共線點的最大數量)—Java
阿新 • • 發佈:2019-02-10
題目描述:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
求二維平面上n個點中,最多共線的點數。思路解析:
遍歷兩層迴圈:第一層迴圈代表起始點,第二層迴圈代表第二個點,兩點定線
特殊情況:
- 點為空,長度為0,return 0
- 只有兩個點,return 2
- 外層迴圈外面定義最大值max初始化為1,用來表示點的個數。因為非空,所以長度至少為1.
在外層迴圈裡面
- 需要定義每次的最大值,即與點 i 共線的最大值,還有重合的點的個數same。
- 如果兩點重合,same就加1,same表示重合的點
- 如果斜率一樣,那就共線,可以使用HashMap來儲存<斜率,個數>,然後內層迴圈結束,就去找到最大值
- 不要忘記每次找到最大值以後就要把same加上
- 斜率是float型別,可以強制型別轉換
- HashMap.values()
- HashMap.get()
- HashMap.put( , )
程式碼:
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ import java.util.HashMap; public class Solution { public int maxPoints(Point[] points) { if(points==null || points.length==0){ return 0; } if(points.length<=2){ return points.length; } int max=1; for(int i=0;i<points.length;i++){ HashMap<Float,Integer> hm = new HashMap<Float,Integer>(); int same=0; int localmax=1; for(int j=0;j<points.length;j++){ if(i==j) continue; if(points[i].x==points[j].x && points[i].y==points[j].y){ same++; continue; } float slope=((float)(points[i].y-points[j].y))/(points[i].x-points[j].x); if(hm.containsKey(slope)) hm.put(slope,hm.get(slope)+1); else hm.put(slope,2); } for(Integer value:hm.values()) localmax = Math.max(localmax,value); localmax+=same; max = Math.max(max,localmax); } return max; } }