鱼C论坛

 找回密码
 立即注册
查看: 2169|回复: 0

[学习笔记] Leetcode 149. Max Points on a Line

[复制链接]
发表于 2020-8-4 04:36:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4
Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6
class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        res = 0
        
        for i in range(n):
            hashmap = collections.defaultdict(int)
            local_max = 0
            same_point = 1
            n1 = points[i]
            
            for j in range(i + 1, n):
                n2 = points[j]
                if n1[0] == n2[0] and n1[1] == n2[1]:
                    same_point += 1
                else:
                    slope = self.get_slope(n1, n2)
                    hashmap[slope] = hashmap[slope] + 1
                    local_max = max(local_max, hashmap[slope])
                    
            res = max(res, local_max + same_point)
        
        return res
        
    def get_slope(self, n1: List[int], n2: List[int]) -> List[int]:
        dx = n2[0] - n1[0]
        dy = n2[1] - n1[1]

        if dy == 0:
            return (n1[1], 0)
        if dx == 0:
            return (0, n1[0])

        d = self.gcd(dx, dy)

        return (dy / d, dx / d)
    
    def gcd(self, a, b): 
        if(b==0): 
            return a 
        else: 
            return self.gcd(b,a%b) 

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-5 00:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表