215_数组中的第K个最大元素

215_数组中的第K个最大元素

 

package 队列.优先级队列;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
 * @author Huangyujun
 *
 */
public class _215_数组中的第K个最大元素 {
    //方法一:利用工具类:Arrays.sort 方法
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k];
    }
    
    //方法二:优先队列【方式2的效率高】
    public int findKthLargest2(int[] nums, int k) {
        //小根堆
        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;    //注意java中 升序是 o1 - o2【小根堆】,  降序才是 o2 - o1【大根堆】
            }
        });
        //逻辑:先存储进去 k容量数据【小根堆】,跟堆顶比【堆顶太小了,抛弃,【调整一个新的最小值于堆顶】,当前值进入维持容量k】
        //每次都抛弃掉最小的【堆顶】,更换进入大的,剩下的就是大的数据呀
        int len = nums.length;
        for(int i = 0; i < len; i++) {
            if(pQueue.size() < k) {
                pQueue.add(nums[i]);
            }else {
                if(pQueue.peek() < nums[i]){
                    pQueue.remove();
                    pQueue.add(nums[i]);
                }
            }
        }
        return pQueue.peek();
    }
    
    //方法三:
    class Solution {
        public int findKthLargest(int[] nums, int k) {
            PriorityQueue<Integer> heap = new PriorityQueue<>();
              //小根堆【默认比较器就是升序的,小根堆】
//            PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
//                @Override
//                public int compare(Integer o1, Integer o2) {
//                    return o1 - o2;    //注意java中 升序是 o1 - o2【小根堆】,  降序才是 o2 - o1【大根堆】
//                }
//            });
            //要找第k 大【不断地维持住一个小根堆的数据】:容量达到k时:
            //(1)当前值比较小,【可能会被调整到堆顶】,容量达标,被poll掉
            //(2)当前值比较大,【存储到后边】,容量达标,被poll掉的是当前最小的那个
            //整个逻辑在于不断地维持住一个小根堆【每次都弹出掉最小的】~~~剩下的便是最大的数据了
            for (int num : nums) {
                heap.add(num);
                if (heap.size() > k) {
                    heap.poll();
                }
            }
            return heap.peek();
        }
    }
}

 

posted @ 2021-12-19 23:36  一乐乐  阅读(20)  评论(0编辑  收藏  举报