[LeetCode]149. Max Points on a Line

0. 問題地址

https://leetcode.com/problems/max-points-on-a-line/

1. 問題簡述

給定n個二位座標點,求最多的處於同一直線的點的個數

2. 解題思路

暴力。O(n*n*log(n)),記錄所有點對的斜率(橫座標相同的話記爲inf),記錄對於一個點。求得包含此點的點對斜率出現的頻次最大值,最終求得結果。

3. 題解代碼

class Point(object):
    def __init__(self, a=0, b=0):
        self.x = a
        self.y = b

def get_slope(a, b):
    if a.x == b.x:
        return float('inf')
    return float(a.y - b.y) / (a.x - b.x)

class Solution(object):
    def maxPoints(self, points):
        """
        :type points: List[Point]
        :rtype: int
        """
        size = len(points) # size(len) of points
        if size <= 2: return size
        pos = [1 for _ in points] # every position with same initial value 1

        # handle same coordinates(same position)
        for i in range(0, size):
            if pos[i] == 0: continue

            for j in range(i + 1, size):
                if points[i].x == points[j].x and points[i].y == points[j].y:
                    pos[i] += 1
                    pos[j] = 0 # mark idx [j] to 0

        ans = max(pos)
        for i in range(0, size):
            if pos[i] == 0: continue

            slope_dict = {}
            for j in range(i + 1, size):
                if pos[j] == 0: continue

                slope = get_slope(points[i], points[j])
                # print "(", points[i].x, ",", points[i].y, ")", "(", points[j].x, ",", points[j].y, ")", slope
                if slope in slope_dict:
                    slope_dict[slope] += pos[j]
                else:
                    slope_dict[slope] = pos[i] + pos[j]

            if slope_dict == {}: continue

            # print slope_dict
            ans = max(ans, max(slope_dict.values()))

        return ans

if __name__ == '__main__':

    sol = Solution()
    points = [Point(84,250),
              Point(0,0),
              Point(1,0),
              Point(0,-70),
              Point(0,-70),
              Point(1,-1),
              Point(21,10),
              Point(42,90),
              Point(1, 1),
              Point(-42,-230),
              ]
    print sol.maxPoints(points), "is answer"
    # [[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[42,90],[-42,-230]]
    # 6 is answer

4. 速度

按理說這個做法很笨,甚至有超時可能,但是看了結果卻發現是在python中最快的。


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