鱼C论坛

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

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

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

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

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

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

  2. Example 1:

  3. Input: [[1,1],[2,2],[3,3]]
  4. Output: 3
  5. Explanation:
  6. ^
  7. |
  8. |        o
  9. |     o
  10. |  o  
  11. +------------->
  12. 0  1  2  3  4
  13. Example 2:

  14. Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
  15. Output: 4
  16. Explanation:
  17. ^
  18. |
  19. |  o
  20. |     o        o
  21. |        o
  22. |  o        o
  23. +------------------->
  24. 0  1  2  3  4  5  6
复制代码

  1. class Solution:
  2.     def maxPoints(self, points: List[List[int]]) -> int:
  3.         n = len(points)
  4.         res = 0
  5.         
  6.         for i in range(n):
  7.             hashmap = collections.defaultdict(int)
  8.             local_max = 0
  9.             same_point = 1
  10.             n1 = points[i]
  11.             
  12.             for j in range(i + 1, n):
  13.                 n2 = points[j]
  14.                 if n1[0] == n2[0] and n1[1] == n2[1]:
  15.                     same_point += 1
  16.                 else:
  17.                     slope = self.get_slope(n1, n2)
  18.                     hashmap[slope] = hashmap[slope] + 1
  19.                     local_max = max(local_max, hashmap[slope])
  20.                     
  21.             res = max(res, local_max + same_point)
  22.         
  23.         return res
  24.         
  25.     def get_slope(self, n1: List[int], n2: List[int]) -> List[int]:
  26.         dx = n2[0] - n1[0]
  27.         dy = n2[1] - n1[1]

  28.         if dy == 0:
  29.             return (n1[1], 0)
  30.         if dx == 0:
  31.             return (0, n1[0])

  32.         d = self.gcd(dx, dy)

  33.         return (dy / d, dx / d)
  34.    
  35.     def gcd(self, a, b):
  36.         if(b==0):
  37.             return a
  38.         else:
  39.             return self.gcd(b,a%b)
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-9 05:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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