public class Solution {
public int thirdMax(int[] nums) {
// Hashset to remove all duplicate elements
HashSet<Integer> set = new HashSet<Integer>();
for (int num : nums)
set.add(num);
// Maintain a min head of size 3 to save the three largest elements in the array.
// After iteration, the peek is the third largest element.
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for (int e : set) {
pq.offer(e);
if (pq.size() > 3) {
pq.poll();
}
}
if (pq.size() == 2) {
pq.poll();
}
return pq.peek();
}
}
Leetcode 414. Third Maximum Number
最新推荐文章于 2022-10-27 15:17:28 发布