248-h215 第k大元素

248-h215 第k大元素_第1张图片

  1. 第k大用小顶堆
  2. 小顶堆 用序号小的减序号大的

关键

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

        PriorityQueue<Integer> smallHeap=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        for (int num : nums) {
            if (smallHeap.size()<k){
                smallHeap.add(num);
            }else {
                if (smallHeap.peek()<num){
                    smallHeap.poll();
                    smallHeap.offer(num);
                }
            }
        }
        return smallHeap.peek();

    }
}

你可能感兴趣的:(算法,算法,leetcode,数据结构)