Leetcode学习笔记:#414. Third Maximum Number

Leetcode学习笔记:#414. Third Maximum Number

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).

实现:

public int thirdMax(int[] nums){
	PriorityQueue<Integer> pq = new PriorityQueue<>();
	Set<Integer> set = new HashSet<>();
	for(int i : nums){
		if(!set.contains(i)){
			pq.offer(i);
			set.add(i);
			if(pq.size() > 3){
				set.remove(pq.poll());
			}
		}
	}
	if(pq.size() < 3){
		while(pq.size() > 1){
			pq.poll();
		}
	}
	return pq.peek();
}

思路:
用一个优先队列和set来遍历数组,如果队列大于三个,则更新队列,把最小的推出去,把比这个数字大的塞进来,再更新set,保持每个相同的数字只有一个。

猜你喜欢

转载自blog.csdn.net/ccystewart/article/details/90147309