[LeetCode][Python]414. Third Maximum Number

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

思路:

  1. 先通過歸并排序把數組有序化,然后除去數組中重復的元素,最后拿到第三大的元素。
  2. Python中有個collections模塊,它提供了個類Counter,用來跟蹤值出現了多少次。注意key的出現順序是根據計數的從大到小。它的一個方法most_common(n)返回一個list, list中包含Counter對象中出現最多前n個元素。
  3. heapq模塊有兩個函數:nlargest() 和 nsmallest() 可以從一個集合中獲取最大或最小的N個元素列表。heapq.nlargest (n, heap) #查詢堆中的最大元素,n表示查詢元素個數
    def thirdMax3(self, nums):
        import heapq
        return heapq.nlargest(3, set(nums))[2 if len(set(nums))>2 else 0]

    def thirdMax4(self, nums):
        nums = sorted(list(set(nums)))
        if len(nums)<3:
            return max(nums)
        else:
            return nums[-3]

其他人的解法:

  1. 把數組中重復的元素通過set去掉,然后remove掉兩次最大值,在整下的元素里面取最大值,就是第三大值。

  2. 取一個數組放入三個最小值元素,然后依次從nums中取值和這三個值比較, 如果比哪個值大,就放在對應的位置。如果最小值元素還在數組里面,就返回最大值,否則就返回第三個元素(也即是第三大元素)

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
   def thirdMax(self, nums):
       """
       :type nums: List[int]
       :rtype: int
       """
       if len(nums) <= 2:
           return max(nums)
       nums = set(nums)
       nums.remove(max(nums))
       nums.remove(max(nums))
       return max(nums)

   def thirdMax2(self, nums):
       v = [float('-inf'), float('-inf'), float('-inf')]
       for num in nums:
           if num not in v:
               if num > v[0]:
                   v = [num, v[0], v[1]]
                   print v
               elif num > v[1]:
                   v = [v[0], num, v[1]]
                   print v
               elif num > v[2]:
                   v = [v[0], v[1], num]
                   print v
       return max(nums) if float('-inf') in v else v[2]



if __name__ == '__main__':
   sol = Solution()
   # s = [3, 2, 1]
   # print sol.thirdMax(s)
   # print sol.thirdMax2(s)
   s = [2, 2, 3, 1]
   # print sol.thirdMax(s)
   print sol.thirdMax2(s)

   s = [1, 2]
   # print sol.thirdMax(s)
   # print sol.thirdMax2(s)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容