Third Maximum Number
来源:互联网 发布:snapgene mac 编辑:程序博客网 时间:2024/06/06 07:50
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.
这道题的测试用例有MIN_VALUE 这个值,因此如果想用三个变量保存前三大的值的话,这三个变量得是long型的,有点蛋疼;于是用priorityqueue做可以避免这些事情;但是这道题是不允许重复的,所以要用一个set保存结果。这样扫一遍就知道第三大是少多了。如果不存在第三大,那么要么是1 要么是2, 2的话再删除一个元素,返回最大值。
代码:
public int thirdMax(int[] nums) { Queue<Integer> queue = new PriorityQueue<>(); Set<Integer> set = new HashSet<>(); for(int num: nums){ if(!set.contains(num)){ set.add(num); queue.offer(num); if(queue.size()>3) queue.poll(); } } if(queue.size()==2) queue.poll(); return queue.peek(); }
0 0
- 414. Third Maximum Number
- LeetCode Third Maximum Number
- Leetcode414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- LeetCode-Third Maximum Number
- leetcode414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- Third Maximum Number
- 414. Third Maximum Number
- LeetCode414 Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- leetcode414: Third Maximum Number
- Third Maximum Number
- 414. Third Maximum Number
- SpringMVC中的视图和视图解析器
- iOS NSNull,nil,Nil的区别
- React Native中定时器的使用
- Zookeeper的watcher数据变更通知机制
- spring的配置文件中mvc:view-controller path使用方法
- Third Maximum Number
- 全面分析 Spring 的编程式事务管理及声明式事务管理
- 在页面里面播放音频文件
- Python学习笔记 __slots__ 限制类属性
- 链表的构建与排序
- springmvc之视图和视图解析器
- MySql基础1
- 【Codeforces 747 C Servers 】+ 思维 或 优先队列
- Lua编程笔录--Lua初识及语法一(注释,变量命名,全局/局部变量,数据类型)