2
头图

The third largest number

Topic Description: to give you a non-empty array, return this array third largest number . If it does not exist, the largest number in the array is returned.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/third-maximum-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Use priority queue

First, initialize a priority queue PriorityQueue as queue, and then traverse the elements in nums. The traversal process is as follows:

  • If the current element is already in the queue, skip it, otherwise add the current element to the queue;
  • If the number of elements in the queue is greater than 3, one element is removed from the queue (the element that overflows is the smallest).

After the traversal is complete, if there are only 3 elements in the queue, the first element in the queue is taken out and returned, which is the third largest element in nums; if there are no 3 elements in the queue, the last element is taken out and returned is in nums The largest element of and return.

import java.util.PriorityQueue;

/**
 * @Author: ck
 * @Date: 2021/9/29 8:08 下午
 */
public class LeetCode_414 {
    /**
     * 使用优先队列
     *
     * @param nums
     * @return
     */
    public static int thirdMax(int[] nums) {
        PriorityQueue<Integer> queue = new PriorityQueue(3);
        for (int num : nums) {
            // 重复的元素过滤掉
            if (!queue.contains(num)) {
                queue.add(num);
            }
            // 因为获取的是第三大的元素,所以当queue中的元素数量超过3时,需要将当前最小的元素取出
            if (queue.size() > 3) {
                queue.poll();
            }
        }
        if (queue.size() == 3) {
            // 当queue只有3个元素时,取最小的即为第三大的元素
            return queue.peek();
        } else {
            // 当queue的元素数量不够3个时,遍历queue取最大的一个
            int max = -1;
            while (!queue.isEmpty()) {
                max = queue.poll();
            }
            return max;
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 2, 5, 3, 5};
        System.out.println(thirdMax(nums));
    }
}
【Daily Message】 The meaning of life is whether it can illuminate oneself while burning oneself.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!