題目:
直線上最多的點數:給定一個二維平面,平面上有 n 個點,求最多有多少個點在同一條直線上。
思路:
使用斜率來判斷,但是在計算斜率時要使用精確計算。
需要考慮不存在斜率,存在斜率和重復點的情況,思路較簡單。
這道題在工商銀行FinTech筆試題里做過。
程序:
from decimal import Decimal
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
num_point = len(points)
if num_point <= 0:
return 0
if num_point == 1:
return 1
if num_point == 2:
return 2
result = 0
for index1 in range(num_point):
myHashMap = {'inf': 0}
twinsPoint = 0
for index2 in range(num_point):
if index1 != index2:
if points[index1][0] == points[index2][0] and points[index1][1] != points[index2][1]:
myHashMap['inf'] += 1
elif points[index1][0] != points[index2][0]:
slope = self.mySlope(points[index1], points[index2])
if slope in myHashMap:
myHashMap[slope] += 1
else:
myHashMap[slope] = 1
else:
twinsPoint += 1
result = max(result, max(myHashMap.values()) + twinsPoint)
return result + 1
def mySlope(self, num1, num2):
return Decimal(num2[1] - num1[1]) / Decimal(num2[0] - num1[0])