取k个最小数

PriorityQueue实现大顶堆


private static final int DEFAULT_INITIAL_CAPACITY = 11;
PriorityQueue maxHeap=new PriorityQueue(DEFAULT_INITIAL_CAPACITY, new Comparator() {
        @Override
        public int compare(Integer o1, Integer o2) {                
            return o2-o1;
        }
    });


例子:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,可以使用大顶堆保存,比堆中的数小就进堆。


import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
   public ArrayList GetLeastNumbers_Solution(int[] input, int k) {
       ArrayList result = new ArrayList();
       int length = input.length;
       if(k > length || k == 0){
           return result;
       }
        PriorityQueue maxHeap = new PriorityQueue(k, new Comparator() {
 
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        for (int i = 0; i < length; i++) {
            if (maxHeap.size() != k) {
                maxHeap.offer(input[i]);
            } else if (maxHeap.peek() > input[i]) {
                Integer temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for (Integer integer : maxHeap) {
            result.add(integer);
        }
        return result;
    }
}


你可能感兴趣的:(取k个最小数)