leetcode每日一题系列-第三大的数-「大根堆」

279 阅读1分钟

leetcode-414-第三大的数

[博客链接]

菜🐔的学习之路

掘金首页

[题目链接]

题目链接

[github地址]

github地址

[题目描述]

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

 

示例 1:

输入:[3, 2, 1]
输出:1
解释:第三大的数是 1

示例 2:

输入:[1, 2]
输出:2
解释:第三大的数不存在, 所以返回最大的数 2

示例 3:

输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1

提示:

  • 1 <= nums.length <= 104
  • 231<=nums[i]<=2311-2^{31} <= nums[i] <= 2^{31} - 1

思路一:大根堆

  • 存入大根堆
  • 定义res作为结果返回
  • 定义max作为最大值元素,当本题无第三大元素返回max
  • 定义step,当且只当比当前res小的时候step--
  • step == 0的时候返回res,否则代表无第三大的元素,返回max
  • 注意本题元素包含Integer.MIN_VALUE所以定义大根堆的时候转换成long或者直接判断大小,不要直接使用减法
public int thirdMax(int[] nums) {
            if (nums.length == 1) {
                return nums[0];
            }
            int step = 2;
            PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    if (o1.equals(o2)) {
                        return 0;
                    }
                    return  o1 <  o2 ? 1 : -1;
                }
            });
            for (int num : nums
            ) {
                pq.add(num);
            }
            int res = pq.poll(), max = res;
            while (step > 0 && !pq.isEmpty()) {
                int temp = pq.poll();
                if (temp < res) {
                    step--;
                }
                res = temp;
            }
            return step == 0 ? res : max;
        }

  • 时间复杂度O(nlgn)
  • 空间复杂度O(n)