LeetCode: Add to List 414. Third Maximum Number
来源:互联网 发布:linux服务器系统占有率 编辑:程序博客网 时间:2024/06/16 10:21
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: 1Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
题意:题目要求输出严格第三大的数,如果没有,则输出最大数。并且要求时间复杂度为O(n)。
分析:
1、严格第三大的数,则冒泡排序并不能确定外循环的次数。所以不能直接使用。
2、严格第三大的数,可以去除重复数据,java中hashset是利用hash函数实现的去重,符合O(n)的要求,然后再进行冒泡排序。
3、看到网络上的记录三个数,扫描一遍数组的算法,其中需要注意点是:数组中可能存在Integer.MIN_VALUE,所以在初始化三个数时需要初始化一个更小的数。另外需要判断如何确定是否存在严格第三大的数。
代码实现的是记录三个数的算法,如下:
class Solution { public int thirdMax(int[] nums) { if(nums==null||nums.length==0) return 0; long first=Long.MIN_VALUE; long second=first; long third=first; int n=nums.length; for(int i=0;i<n;i++){ if(nums[i]>first) { third=second; second=first; first=nums[i]; } else if(nums[i]<first&&nums[i]>second) { third=second; second=nums[i]; } else if(nums[i]<second&&nums[i]>third) third=nums[i]; } return (third==Long.MIN_VALUE||third==second)? (int)first:(int)third; }}
阅读全文
0 0
- LeetCode: Add to List 414. Third Maximum Number
- 414. Third Maximum Number Add to List
- 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
- 图文并茂的Python散点图教程
- opencv: 视频中提取帧图片并保存(cv2.VideoCapture)
- C/C++、JAVA、C#之间的关系和区别?
- 用eclipse启动tomact后,访问主页404错误解决
- C和指针 13章练习题算是从书上转载的吧
- LeetCode: Add to List 414. Third Maximum Number
- 如何轻松学习C语言
- android Rsa加密 与 openssl库互通
- hadoop 多个Mapper和Reducer的Job
- Unity如何调用安卓手机摄像头实现拍照和录像
- 不得不看的Java代码性能优化总结
- 51Nod 1118 机器人走方格(dp/快速幂)
- Web应用指纹检测
- 单点登录