파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2023. 1. 8. 23:45

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

 

Max Points on a Line - LeetCode

Max Points on a Line - Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.   Example 1: [https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg

leetcode.com

기울기를 map으로 저장해서 처리하면 됨.

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        if len(points) <= 2:
            return len(points)

        def line(p1, p2):
            if p2[0] - p1[0] == 0:
                return (p1[0])
            slope = (p2[1]-p1[1]) / (p2[0]-p1[0])
            b = p1[1] - slope * p1[0]
            return (slope, '%.5f' %b)
        
        res = 0

        for i in range(len(points)):
            count = defaultdict(int)
            for j in range(i+1, len(points)):
                count[line(points[i], points[j])] += 1
            if count:
                res = max(res, max(count.values()))

        return res + 1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2023.01.10
Today's Challenge  (0) 2023.01.09
Today's Challenge  (0) 2023.01.07
Today's Challenge  (0) 2023.01.06
Today's Challenge  (0) 2023.01.05
Comments