其他分享
首页 > 其他分享> > leetcode (堆->simple)703,1046,前k大/小数

leetcode (堆->simple)703,1046,前k大/小数

作者:互联网

703

第K大

 

 

class KthLargest {

    private PriorityQueue<Integer> heap ;
    
    private int k;

    public KthLargest(int k, int[] nums) {
heap = new PriorityQueue<>(k,(k1,k2)->k1.compareTo(k2));
        this.k = k;
        for (int i = 0; i < nums.length; i++) {
            if (i < k){
                heap.add(nums[i]);
            }else {
                if (nums[i] >= heap.peek()){
                    heap.poll();
                    heap.add(nums[i]);
                }
            }
        }
    }
    
    public int add(int val) {
        if (heap.size() < k){
            heap.add(val);
        } else if (val >= heap.peek()){
            heap.poll();
            heap.add(val);
        }
        return heap.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

 

1046

 

 

也是用堆的特性来做

        PriorityQueue<Integer> heap = new PriorityQueue<>((k1,k2)->k2.compareTo(k1));
        for (int i = 0; i < stones.length; i++) {
            heap.offer(stones[i]);
        }

        while (heap.size() > 1){
            Integer x1 = heap.poll();
            Integer x2 = heap.poll();
            if (x1 != x2){
                heap.offer(Math.abs(x1-x2));
            }
        }
        if (heap.isEmpty()){
            return 0;
        }

        return heap.poll();

 

 

前大/小K 个数

    public static int[] getLeastNumbers(int[] arr,int k) {
        if (k ==0 || arr.length == 0){
            return new int[0];
        }
        PriorityQueue<Integer> heap = new PriorityQueue<>((k1,k2)->k2.compareTo(k1));
        for (int i = 0; i < arr.length; i++) {
            if (i < k){
                heap.offer(arr[i]);
            }else {
                if (arr[i] < heap.peek()){
                    heap.poll();
                    heap.offer(arr[i]);
                }
            }
        }
        int size = heap.size(),ks = 0;
        int[] result = new int[size];
        while (ks<size){
            result[ks++] = heap.poll();
        }

        return result;
    }

 

标签:1046,k2,simple,k1,int,add,heap,poll,leetcode
来源: https://www.cnblogs.com/hetutu-5238/p/14345189.html