[LeetCode]414. Third Maximum Number
来源:互联网 发布:ewb仿真软件简介 编辑:程序博客网 时间:2024/06/16 17:10
题目描述: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.
分析:返回第三大的数,如果不存在则返回最大的数。
解题思路:遍历,将first、second、third存储并返回第三大的数,如果不存在则返回最大的数。
public int thirdMax(int[] nums) { Integer first = null; Integer second = null; Integer third = null; for(int i=0;i<nums.length;i++){ if(first==null||nums[i]>first){ third = second; second = first; first = nums[i]; }else if(second==null||nums[i]>second){ if(nums[i]==first)continue; third = second; second = nums[i]; }else if(third==null||nums[i]>third){ if(nums[i]==second)continue; third = nums[i]; } } return third==null?first:third; }
- leetcode 414. Third Maximum Number
- LeetCode:414. Third Maximum Number
- LeetCode-414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- [Leetcode]414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- <leetcode>414. Third Maximum Number
- Leetcode 414. Third Maximum Number
- 【LeetCode】 414. Third Maximum Number
- [leetcode]414. Third Maximum Number
- Leetcode-414. Third Maximum Number
- [leetcode]414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- [LeetCode]414. Third Maximum Number
- Leetcode-414. Third Maximum Number
- 【LeetCode】414. Third Maximum Number
- LeetCode 414. Third Maximum Number
- 【Leetcode】414. Third Maximum Number
- [NLP论文阅读] Word Embedding based on Fixed-Size Ordinally Forgetting Encoding
- 磁盘的读写原理
- C++中const的作用/用法
- Python SMTP发送邮件
- 动态日历
- [LeetCode]414. Third Maximum Number
- 沉浸式通知栏自动退出的问题
- log4j输出多个自定义日志文件
- kmp(字符串匹配)
- Git fetch和git pull的区别
- Java WEB系统国际化经验总结
- SDWebImage底层的实现
- 【转】函数的声明和定义
- Codeforces Round #338 (Div. 2)-D Multipliers(所有因数之积)