Java for LeetCode 149 Max Points on a Line

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.