您的位置:首页 > 其它

【LeetCode】414. Third Maximum Number 解题报告

2018-02-05 12:31 585 查看

【LeetCode】414. Third Maximum Number 解题报告

标签: LeetCode

题目地址:https://leetcode.com/problems/third-maximum-number/description/

题目描述:

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.

解题方法

方法一:

最基本的方法,找到最大值,然后每次把最大值移除,这样重复三次就得到了第三大的值。

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def setMax(nums):
_max = max(nums)
for i, num in enumerate(nums):
if num == _max:
nums[i] = float('-inf')
return _max
max1 = setMax(nums)
max2 = setMax(nums)
max3 = setMax(nums)
return max3 if max3 != float('-inf') else max(max1, max2)


方法二:

用set去算,set的时间复杂度是O(n)。set的remove()方法可以去除某个值,不过每次只能去除一个。

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
if len(nums_set) < 3:
return max(nums_set)
nums_set.remove(max(nums_set))
nums_set.remove(max(nums_set))
_max = max(nums_set)
return _max


日期

2018 年 2 月 4 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: