[leetcode: Python]414. Third Maximum Number
2017-05-16 17:34
239 查看
Title:
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:
Example 2:
Example 3:
方法一:56ms
方法二:39ms
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.
方法一:56ms
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ n1 = set(nums) s1 = [] for i in n1: s1.append(i) s1.sort() s = s1[::-1] if len(s) < 3: return s[0] return s[2]
方法二:39ms
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ a=set(nums) if len(a)<3: return max(a) else: a.remove(max(a)) a.remove(max(a)) return max(a)
相关文章推荐
- 【LeetCode with Python】 Wildcard Matching
- 【LeetCode with Python】 Generate Parentheses
- 【LeetCode with Python】 Remove Duplicates from Sorted Array
- 【LeetCode with Python】 Binary Tree Preorder Traversal
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- 【LeetCode with Python】 Binary Tree Inorder Traversal
- 【LeetCode with Python】 Pow(x, n)
- 【LeetCode with Python】 Maximum Subarray
- 【LeetCode with Python】 Insertion Sort List
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Swap Nodes in Pairs
- 【LeetCode with Python】 Reverse Words in a String
- 【LeetCode with Python】 Remove Duplicates from Sorted List
- 【LeetCode with Python】 String to Integer (atoi)
- 【LeetCode with Python】 LRU Cache
- 【LeetCode with Python】 Remove Element
- 【LeetCode with Python】 Validate Binary Search Tree
- 【LeetCode with Python】 Pascal's Triangle
- 【LeetCode with Python】 Balanced Binary Tree
- 【LeetCode with Python】 Minimum Depth of Binary Tree