[Leetcode] - Max Points on a Line

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

這道題第一次見到是在Cracking上面。第一次做的時候感覺自己的想法好複雜啊,然後看答案之後才豁然開朗。哎,還是菜。大概的思路是這樣的。對於一條直線而言,在解析幾何中有若干種表示方法,我記得中學學過3,4種吧。具體到這道題而言,斜截式無疑是最方便也最合適的表示方法了。也就是說,對於一條直線,用公式y=kx+b將其表示出來。那麼,如果兩條直線重合的話,它們的斜率k和截距b必須相等才行。給定兩點,可以通過簡單的數學推導求出它們所在直線的斜率和截距。沿着這個思路想下去,我們還需要一個HashMap用來存儲已經遇到過的直線和其經過的點的個數。在我的程序裏面,是這樣定義的,HashMap<Line, ArrayList<Point>>。也就是說,每次根據兩個點,計算得到一條直線,然後看其是否在HashMap之中,然後把原先沒有的點補充到key裏面,最後再用一個變量max來記錄最大的點數,每次點有更新的時候,都看看是否需要更新max。這樣做的時間複雜度是O(n2)。應該還會有更好的方法,等想出來或者查到了再更新吧。

還有三個問題值得注意。首先,因爲斜率和截距是double類型的變量,所以在比較的時候,必須設定一個epsilon,如果兩條直線的斜率和截距的差值均小於epsilon的話,它們纔算重合。這是因爲浮點數無法精確處理的原因。其次,如果直線垂直於X軸,那麼其斜率將是無窮大。爲了處理這種情況,我們可以在Line這個類中增加一個boolean屬性,這個屬性用於表示該直線是否垂直於X軸,然後在比較的時候稍加註意這個edge case便好。最後,必須要注意,爲了使得HashMap正常工作,在Line這個類中,我們必須要重寫equals和hashcode這兩個方法。記住,這兩個方法必須同時重寫才行。簡單的理解,hashcode用於從一個array中找到一個key對應的value應該被存放的位置。但是爲了解決衝突的問題,array存的是鏈表而不是value,所以,可能還要繼續按照鏈表往下找。所以說,equals的兩個object必然有相同的hashcode,但是hashcode相同的兩個object並不一定會是equals的關係。把javadoc裏面關於Object類的hashcode和equals方法的描述貼到下面,以後忘了就看看。


代碼如下:

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    public int maxPoints(Point[] points) {
        if(points==null || points.length==0) return 0;
        if(points.length==1) return 1;
        
        HashMap<Line, ArrayList<Point>> map = new HashMap<Line, ArrayList<Point>>();
        int max = 0;
        for(int i=0; i<points.length; i++) {
            for(int j=i+1; j<points.length; j++) {
                Line line = new Line(points[i], points[j]);
                if(!map.containsKey(line)) {
                    map.put(line, new ArrayList<Point>());
                }
                if(!map.get(line).contains(points[i])) map.get(line).add(points[i]);
                if(!map.get(line).contains(points[j])) map.get(line).add(points[j]);
                if(map.get(line).size()>max) max=map.get(line).size();
            }
        }
        return max;
    }
}

class Line {
    public double slope;
    public double intersect;
    private static double epsilon = 0.0001;
    private boolean vertical = false;
    
    public Line(Point a, Point b) {
        if(Math.abs(a.x-b.x) < epsilon) {   // vertical line
            vertical = true;
            intersect = a.x;
        }
        else {  // non-vertical line
            slope = ((double)(a.y-b.y))/(a.x-b.x);
            intersect = ((double)(a.x*b.y-a.y*b.x))/(a.x-b.x);
        }
    }
    
    @Override
    public boolean equals(Object o) {
        Line l = (Line) o;
        if(isEqual(slope, l.slope) && isEqual(intersect, l.intersect) && vertical==l.vertical) {
            return true;
        }
        else {
            return false;
        }
    }
    
    @Override
    public int hashCode() {
        int sl = (int)(slope * 1000);
        int in = (int)(intersect * 1000);
        return sl | in;
    }
    
    public boolean isEqual(double a, double b) {
        return (Math.abs(a-b) < epsilon);
    }
}


public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)


public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value xx.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and yx.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values xy, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value xx.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章