给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
解释:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
示例 2:
输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
? https://leetcode-cn.com/problems/max-points-on-a-line
对每一个点算出其他各点与它的斜率,用哈希表存储某一斜率被计算出来的次数,也就是在该斜率的直线上有多少个点。
测试数据中的点的情况有3种:
1. 斜率正常存在
2. 斜率不存在,横坐标相同
3. 和之前的点相同 如: [(0,0),(0,0),(0,0)] 最多有3个点在同一条直线上
from decimal import Decimal
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if not len(points):
return 0;
res = 0;
for i in range(len(points)):
hash_map = dict();
v = 0
more = 0
for j in range(len(points)):
if j != i:
if points[i][0] != points[j][0]:
hash_map[Decimal((points[i][1] - points[j][1])) / Decimal((points[i][0] - points[j][0]))] = hash_map.get(Decimal((points[i][1] - points[j][1])) / Decimal((points[i][0] - points[j][0])),0) + 1
elif points[i][0] == points[j][0] and points[i][1] != points[j][1]:
v += 1
elif points[i][0] == points[j][0] and points[i][1] == points[j][1]:
more += 1
for x in hash_map:
res = max(res,hash_map[x] + 1 + more)
res = max(res,v + 1 + more)
return res;