【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 日相关文章推荐
- [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- 【LeetCode】763. Partition Labels 解题报告
- LeetCode 136. Single Number 解题报告
- leetcode解题报告(14):Max Consecutive Ones
- 【LeetCode】Word Break 解题报告
- [leetcode] 346. Moving Average from Data Stream 解题报告
- LeetCode 解题报告 Sort List
- LeetCode-Basic Calculator II-解题报告
- 【LeetCode】Dungeon Game 解题报告【Solution】
- Leetcode Word Ladder II 解题报告
- 【LeetCode】Reverse Vowels of a String 解题报告
- [Leetcode] 257. Binary Tree Paths 解题报告
- [Leetcode] 128. Longest Consecutive Sequence 解题报告
- LeetCode-Implement Stack using Queues-解题报告
- Leetcode #347. Top K Frequent Elements 前K高频数 解题报告
- [Leetcode] 513. Find Bottom Left Tree Value 解题报告
- [leetcode]142. Linked List Cycle II@Java解题报告
- [Leetcode] 515. Find Largest Value in Each Tree Row 解题报告
- LeetCode:Sqrt(x) 解题报告
- leetcode 715. Range Module 解题报告