zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    线程阻塞工具:LockSupport
    jenkins
    Mysql中MVCC的使用及原理详解
    你知道 hash 的实现吗?为什么要这样实现?
    为什么哈希表的容量一定要是 2的整数次幂?
    同步异步 阻塞 非阻塞
    MFC
    MFC
    MFC
    MFC
  • 原文地址:https://www.cnblogs.com/hetutu-5238/p/14345189.html
Copyright © 2011-2022 走看看