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.
思路:
- 先通過歸并排序把數(shù)組有序化,然后除去數(shù)組中重復(fù)的元素徙邻,最后拿到第三大的元素。
- Python中有個collections模塊对粪,它提供了個類Counter,用來跟蹤值出現(xiàn)了多少次装蓬。注意key的出現(xiàn)順序是根據(jù)計數(shù)的從大到小著拭。它的一個方法most_common(n)返回一個list, list中包含Counter對象中出現(xiàn)最多前n個元素。
- heapq模塊有兩個函數(shù):nlargest() 和 nsmallest() 可以從一個集合中獲取最大或最小的N個元素列表牍帚。heapq.nlargest (n, heap) #查詢堆中的最大元素儡遮,n表示查詢元素個數(shù)
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]
其他人的解法:
把數(shù)組中重復(fù)的元素通過set去掉,然后remove掉兩次最大值暗赶,在整下的元素里面取最大值鄙币,就是第三大值。
取一個數(shù)組放入三個最小值元素忆首,然后依次從nums中取值和這三個值比較爱榔, 如果比哪個值大被环,就放在對應(yīng)的位置糙及。如果最小值元素還在數(shù)組里面,就返回最大值筛欢,否則就返回第三個元素(也即是第三大元素)
#!/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)