码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 414. Third Maximum Number

时间:2016-12-24 07:48:28      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:max   color   list   需要   not   etc   put   note   pointer   

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

标签:max   color   list   需要   not   etc   put   note   pointer   

原文地址:http://www.cnblogs.com/lettuan/p/6216602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!