[leetcode]Max Points on a Line @ Python


原題地址:https://oj.leetcode.com/problems/max-points-on-a-line/

題意:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

解題思路:找到平面上在一條直線上最多的點。點在同一條直線上意味着這些點的斜率是一樣的,那么可以考慮使用哈希表來解決,{斜率:[點1,點2]}這樣的映射關系。這里有幾個需要考慮的要點:1,有可能是斜率無窮大。2,有可能有相同的點,比如[(1,2),(1,2)]。

代碼:

# Definition for a point
# class Point:
#     def __init__(self, a=0, b=0):
#         self.x = a
#         self.y = b

class Solution:
    # @param points, a list of Points
    # @return an integer
    def maxPoints(self, points):
        length = len(points)
        if length < 3: return length
        res = -1
        for i in range(length):
            slope = {'inf': 0}
            samePointsNum = 1
            for j in range(length):
                if i == j:
                    continue
                elif points[i].x == points[j].x and points[i].y != points[j].y:
                    slope['inf'] += 1
                elif points[i].x != points[j].x:
                    k = 1.0 * (points[i].y - points[j].y) / (points[i].x - points[j].x)
                    if k not in slope:
                        slope[k] = 1
                    else:
                        slope[k] += 1
                else:
                    samePointsNum += 1
            res = max(res, max(slope.values()) + samePointsNum)
        return res

 


免責聲明!

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



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