標籤:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
解題思路:
本題主要需要考慮到斜線的情況,可以分別計算出過points[i]直線最多含幾個點,然後算出最大即可,由於計算points[i]的時候,前面的點都計算過了,所以不需要把前面的點考慮進去,所以問題可以轉化為過points[i]的直線最大點的個數,解題思路是用一個HashMap儲存斜率,遍曆points[i]後面每個點,看看和points[i]的斜率是否出現過,這裡有個問題,如何儲存斜率,理想狀況下,斜率應該用一個String表示,如(0,0)和(2,4)可以儲存為"1k2"這樣的類型,這會涉及到求最大公約數的問題,實現起來比較麻煩,實際上直接用double表示即可通過,這是因為((double)1/((double)Integer.MAX_VALUE-(double)Integer.MIN_VALUE))是能輸出2.3283064370807974E-10的。因此,我們直接用double即可。
JAVA實現如下:
public int maxPoints(Point[] points) {if (points.length <= 2)return points.length;int max = 2;for (int i = 0; i < points.length; i++) {int pointMax = 1, samePointCount = 0;HashMap<Double, Integer> slopeCount = new HashMap<Double, Integer>();Point origin = points[i];for (int j = i + 1; j < points.length; j++) {Point target = points[j];if (origin.x == target.x && origin.y == target.y) {samePointCount++;continue;}double k;if (origin.x == target.x)k = Float.POSITIVE_INFINITY;else if (origin.y == target.y)k = 0;elsek = ((double) (origin.y - target.y))/ (double) (origin.x - target.x);if (slopeCount.containsKey(k))slopeCount.put(k, slopeCount.get(k) + 1);elseslopeCount.put(k, 2);pointMax = Math.max(pointMax, slopeCount.get(k));}max = Math.max(max, pointMax + samePointCount);}return max; }
Java for LeetCode 149 Max Points on a Line