作者: 不再_犹豫 | 来源:发表于2020-07-29 09:28 被阅读0次

    Java优先队列

    static Comparator<Integer> cmp = new Comparator<Integer>(){
        public int compare(Integer e1,Integer e2){
            return e1 - e2;//默认升序排列,大根堆
        }
    };
    Queue<Integer> q = new PriorityQueue(cmp);
    
    剑指 Offer 40. 最小的k个数
        static Comparator<Integer> cmp = new     Comparator<Integer>(){
            public int compare(Integer e1,Integer e2){
                return e2 - e1;
            }
        };
        public int[] getLeastNumbers(int[] arr, int k) {
            if(arr.length ==0 || k == 0) return new int[0];
            int []res = new int[k];
            Queue<Integer> q = new PriorityQueue(cmp);
            for(int i = 0;i < k;i++){
                q.offer(arr[i]);
            }
            for(int i = k;i < arr.length;i++){
                if(arr[i] < q.peek()){
                    q.poll();
                    q.offer(arr[i]);
                }
            }
            int idx = 0;
            while(!q.isEmpty()) res[idx++] = q.poll();
            return res;
        }
    ``
    

    相关文章

      网友评论

          本文标题:

          本文链接:https://www.haomeiwen.com/subject/qtocrktx.html