Leetcode練習(Python):哈希表類:第149題:直線上最多的點數:給定一個二維平面,平面上有 n 個點,求最多有多少個點在同一條直線上。


題目:
直線上最多的點數:給定一個二維平面,平面上有 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])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM