高频刷题-215 Kth Largest Element in an array

这篇博客介绍了三种方法来解决寻找数组中第K大的元素问题。方法1利用了大根堆,时间复杂度为O(n log n),在nums数量远大于k时较为高效。方法2直接排序数组,然后返回倒数第k个元素,时间复杂度为O(n log n)。方法3使用小根堆,当堆大小小于k时添加元素,如果新元素大于堆顶则替换,适合nums数量大于k的情况。每种方法都有其适用场景,考虑性能和数据规模选择合适的方法。
摘要由CSDN通过智能技术生成

https://leetcode.com/problems/kth-largest-element-in-an-array/

解法1:

public int findKthLargest(int[] nums, int k) {

        // 排序并且放入大根堆中

        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);

        for (int i = 0; i < nums.length; i++) {

            queue.offer(nums[i]);

        }

        int number = 0;

        while(k-- > 0) {

            number = queue.poll();   

        }

        //取出第K个

        return number;

    }

 

解法2:

public int findKthLargest(int[] nums, int k) {

       

        Arrays.sort(nums);

        return nums[nums.length - k];

    }

解法3:

public int findKthLargest(int[] nums, int k) {
        //使用小根堆,当堆中数量小于k时,将数据放入堆中,如果当前数大于堆顶的数,则弹出,将当前数放入堆中
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int num : nums) {
            if (queue.size() < k) {
                queue.offer(num);
            } else {
                if (num > queue.peek()) {
                    queue.poll();
                    queue.offer(num);
                }
            }
        }
        return queue.peek();
    }

对于算法中常见的PriorityQueue ,它的时间复杂度和实现如下:

Java PriorityQueue Time Complexity

  • For enqueing and dequeing methods, the time complexity is O(log(n))
  • For the remove(Object) and contains(Object) methods, the time complexity is linear.
  • For the retrieval methods, it has constant time complexity.

三种方法适用于不同的内容,例如如果nums的数量和k的数量的相对关系,如果nums数量>>k数量,则方法3较好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值