首页 > 代码库 > Leetcode 414. Third Maximum Number

Leetcode 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 class Solution(object):
 2     def thirdMax(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         a = b = c = None
 8         for x in nums:
 9             if x > a:
10                 a, b, c = x, a, b
11             if b<x<a:
12                 a, b, c = a, x, b
13             if c<x<b:
14                 a, b, c = a, b, x
15         if c == None:
16             return a
17         else:
18             return c

本题学到的是,python的判别条件里可以用 a<x<b 这种格式,方便了很多。另外就是L7里面a = b = c = None。这种赋值是可以的。但是需要注意由于Python的 = 其实是pointer。所以如果用一下的code,我们其实同时改变了a和b的值(变成了[1,2])。以为他们是指向同一个对象的。

1 a = b = [1]
2 a.append(2)

 

 



Leetcode 414. Third Maximum Number