1. 程式人生 > >leetcode149- Max Points on a Line- hard

leetcode149- Max Points on a Line- hard

hat pla 而不是 mat 起點 ash esc ont 情況

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

考數學和摳細節。O(n2)。每對點都要遍歷。先固定第一個點,從第一個點開始跟後面每個點計算斜率,存到斜率-計數的<Double,Integer>map裏。每個點為起點的斜率遍歷過了以後,打一下擂臺(count + dup)。

細節:1.點重復(用dup計數,這個要加到所有斜率上面的)

2. 斜率為正無窮,用double(Integer.MAX_VALUE)計數

3. 斜率為0,用0計數(避免+-0情況)

4. 普通斜率(最好用GCD最小公倍數求一下然後存這個約分了的x-y-計數對而不是存斜率-計數對,map<Integer x,Map<Integer y,Integer cnt>>,因為這樣能避免很近的大點問題,比如[0,0], [1000000,10000001],[10000001, 100000002]這種,但實現太麻煩了不做這個優化也行)

實現

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 
*/ class Solution { public int maxPoints(Point[] points) { if (points == null) { return 0; } Map<Double, Integer> map = new HashMap<>(); int dup = 0; int max = 0; for (int i = 0; i < points.length; i++) { map.clear(); dup
= 0; map.put((double)Integer.MIN_VALUE, 1); for (int j = i + 1; j< points.length; j++) { // 1. duplicate point if (points[i].x == points[j].x && points[i].y == points[j].y) { dup++; continue; } double slope; if (points[i].x == points[j].x) { slope = (double)Integer.MAX_VALUE; } else if (points[i].y == points[j].y) { slope = 0.0; } else { slope = (double)(points[i].y - points[j].y) / (double)(points[i].x - points[j].x); } if (map.containsKey(slope)) { map.put(slope, map.get(slope) + 1); } else { map.put(slope, 2); } } for (int cnt : map.values()) { max = Math.max(max, cnt + dup); } } return max; } }

leetcode149- Max Points on a Line- hard