149. Max Points on a Line - python3

1307 ワード

149. 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.
y=ax+bの形で各点を傾けておけばいいのに...
すべての組み合わせでこの傾きを求めて...私にはできません.

Solution 1: Runtime: 48 ms - 96.96% / Memory Usage: 14 MB - 99.22%

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        def helper(currentPoint, points):
            slopes,duplicates,ans = {},0,0
            x1, y1 = currentPoint
            for x2, y2 in points:
                # If the points are same inc duplicate counter
                if x1 == x2 and y1 == y2:
                    duplicates += 1
                # else find the slop and add in dic
                else:
                    slope = (x2 - x1) / (y2 - y1) if y2 != y1 else 'inf'
                    count = slopes.get(slope, 0) + 1
                    slopes[slope] = count
                    ans = max(ans, count)
            return ans + 1 + duplicates
        ans = 0
        while points:
            currentPoint = points.pop()
            ans = max(ans, helper(currentPoint, points))
        return ans
pop currentPoint(x 1)を1つのポイントで1つずつつかむ
残りの点をx 2に位置決めし、繰り返し検査して傾斜を求める
  • get(a,b)=>aを見つけます.そうでなければ、デフォルト=b、
  • です.