What is the most efficient algorithm to find a straight line that goes through most points?

前端 未结 7 1892
渐次进展
渐次进展 2020-11-29 18:30

The problem:

N points are given on a 2-dimensional plane. What is the maximum number of points on the same straight line?

The problem has O(N2<

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 18:34

    Again an O(n^2) solution with pseudo code. Idea is create a hash table with line itself as the key. Line is defined by slope between the two points, point where line cuts x-axis and point where line cuts y-axis.

    Solution assumes languages like Java, C# where equals method and hashcode methods of the object are used for hashing function.

    Create an Object (call SlopeObject) with 3 fields

    1. Slope // Can be Infinity
    2. Point of intercept with x-axis -- poix // Will be (Infinity, some y value) or (x value, 0)
    3. Count

    poix will be a point (x, y) pair. If line crosses x-axis the poix will (some number, 0). If line is parallel to x axis then poix = (Infinity, some number) where y value is where line crosses y axis. Override equals method where 2 objects are equal if Slope and poix are equal.

    Hashcode is overridden with a function which provides hashcode based on combination of values of Slope and poix. Some pseudo code below

    Hashmap map;
    foreach(point in the array a) {
        foeach(every other point b) {
            slope = calculateSlope(a, b);
            poix = calculateXInterception(a, b);
            SlopeObject so = new SlopeObject(slope, poix, 1); // Slope, poix and intial count 1.
            SlopeObject inMapSlopeObj = map.get(so);
            if(inMapSlopeObj == null) {
                inMapSlopeObj.put(so);
            } else {
                inMapSlopeObj.setCount(inMapSlopeObj.getCount() + 1);
            }
        }
    }
    SlopeObject maxCounted = getObjectWithMaxCount(map);
    print("line is through " + maxCounted.poix + " with slope " + maxCounted.slope);
    

提交回复
热议问题