LeetCode題解(0414):數組中第三大的數(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(n) O(1) 64ms (83.71%)
Ans 2 (Python) O(1) 52ms (99.70%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(直接尋找第三大的值):

def thirdMax(self, nums: List[int]) -> int:
    nums = set(nums)
    if len(nums) < 3:
        return max(nums)
    max1 = min(nums)
    max2 = max1
    max3 = max2
    for n in nums:
        if n > max1:
            max3 = max2
            max2 = max1
            max1 = n
        elif n > max2:
            max3 = max2
            max2 = n
        elif n > max3:
            max3 = n
    return max3

解法二(逐個刪除最大值):

def thirdMax(self, nums: List[int]) -> int:
    nums = set(nums)
    if len(nums) < 3:
        return max(nums)
    nums.remove(max(nums))
    nums.remove(max(nums))
    return max(nums)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章