[剑指 offer]面试题40. 最小的k个数

最小k个数
class Solution {

    private int size;
    private int[] arr;

    //把输入的数组堆化
    private void heapify(int[] arr){
        this.arr = new int[arr.length];
        for(int i = 0; i < arr.length; i++)
            this.arr[i] = arr[i];
        size = this.arr.length;
        for(int i = parent(arr.length - 1); i >= 0; i--)
            siftDown(i);
    }

    public int extractMin(){
        int ret = arr[0];
        swap(0, size - 1);
        arr[size - 1] = -1;
        size --;
        siftDown(0);
        return ret;
    }

    //ok
    private void siftDown(int k){

        while(leftChild(k) < size){
            int j = leftChild(k);
            if(j + 1 < size &&
             arr[j + 1] < arr[j]){
                j++;
            }
            if(arr[k] <= arr[j]){
                break;
            }
            swap(k, j);
            k = j;
        }
    }

    private void swap(int i, int j){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    private int leftChild(int k){
        return 2 * k + 1;
    }

    private int rightChild(int k){
        return 2 * k + 2;
    }

    private int parent(int k){
        return (k - 1) / 2;
    }

    public int[] getLeastNumbers(int[] arr, int k) {
        heapify(arr);
        int[] res = new int[k];
        for(int i = 0;i < k;i++){
            res[i] = extractMin();
            // System.out.println("print" + res[i]);
            // System.out.println("size: " + this.size);
        }
        return res;
    }
}

你可能感兴趣的:([剑指 offer]面试题40. 最小的k个数)