[Leetcode][python]Max Points on a Line/直线上最多的点数

- 日理万妓 2022-06-03 04:51 711阅读 0赞

题目大意

在一个平面上有n个点,求一条直线最多能够经过多少个这些点。

解题思路

哈希表保存斜率

代码

注意有个坑:
测试集[[0,0],[94911151,94911150],[94911152,94911151]],由于数字大,直接内置除法斜率会算成一样的,用numpy库运算

  1. import numpy as np
  2. class Solution:
  3. def maxPoints(self, points):
  4. """
  5. :type points: List[Point]
  6. :rtype: int
  7. """
  8. n = len(points)
  9. slope_map = {}
  10. result = 0
  11. for i in range(n):
  12. # print(slope_map)
  13. slope_map.clear()
  14. same, vertical = 1, 0
  15. slope_max = 0
  16. for j in range(i + 1, n):
  17. dx, dy = points[i].x - points[j].x, points[i].y - points[j].y
  18. if dx == dy == 0: # 同一个点
  19. same += 1
  20. elif dx == 0: # 斜率无限大,垂直
  21. vertical += 1
  22. else:
  23. slope = (dy * np.longdouble(1)) / dx
  24. # slope = float(dy) / float(dx)
  25. # print(slope)
  26. slope_map[slope] = slope_map.get(slope, 0) + 1
  27. slope_max = max(slope_max, slope_map[slope])
  28. result = max(result, max(slope_max, vertical) + same)
  29. return result

总结

发表评论

表情:
评论列表 (有 0 条评论,711人围观)

还没有评论,来说两句吧...

相关阅读