python-3.x - 使用 python 3 在一条线上的最大点数
问题描述
算法题:给定二维平面上的 n 个点,找出位于同一直线上的最大点数。
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
工作 python 3 代码如下: 想知道片段 1d[slope] = d.get(slope, 1) + 1
正在工作
但是为什么即使片段 1 和 2 相同,此片段 2 也无法正常工作,例如 2
if slope in d:
d[slope] += 1
else:
d[slope] = 1
def gcd(self, a, b):
if b == 0:
return a
return self.gcd(b, a%b)
def get_slope(self, p1, p2):
dx = p1[0] - p2[0]
dy = p1[1] - p2[1]
c = self.gcd(dx, dy)
dx /= c
dy /= c
return str(dy) + "/" + str(dx)
def is_same_points(self, p1:List[int], p2:List[int]):
return p1[0] == p2[0] and p1[1] == p2[1]
def maxPoints(self, points: List[List[int]]) -> int:
if not points:
return 0
n = len(points)
count = 1
for i in range(0, n):
d = {}
duped = 0
localmax = 1
p1 = points[i]
for j in range(i+1, n):
p2 = points[j]
if self.is_same_points(p1, p2):
duped += 1
else:
slope = self.get_slope(p1, p2)
# 1) not work: output is 3 in example 2
# if slope in d:
# d[slope] += 1
# else:
# d[slope] = 1
# 2) works: correct output 4 for example 2
d[slope] = d.get(slope, 1) + 1
localmax = max(localmax, d[slope]);
count = max(count, localmax + duped)
return count
解决方案
有趣的问题和很好的解决方案。
注释掉的代码不起作用的原因是:
else:
d[slope] = 1 ## correct would be d[slope] = 2
每 2 个点都在同一条线上,前两个 p1 p2 只计算一个点,因此在最终答案中你会少一个点。
推荐阅读
- coq - 自然数列表中的最大值
- javascript - 在表中添加多行并在同一行中添加嵌套行
- c# - 如何使用itext7从标记的pdf中的结构元素中提取文本
- html - 将 svg 路径分成 3 部分
- java - 在 MVC 测试中使用 Hamcrest 匹配 LocalDateTime
- php - 将值从一个表插入到另一个表sql和php
- python - 如何解决超时异常硒python?
- html - 带有反应的导航菜单
- cross-compiling - 如何在amd64上安装OpenGL arm64库进行交叉编译
- matlab - 如何在 Octave 中打印 symfunc 使其看起来是人工键入的而不是人工编写的?