最小的K个数

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

public class Solution {
	public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
		ArrayList<Integer> res = new ArrayList<>();
		if (k < 1 || k > input.length) {
			return res;
		}
		int[] help = new int[k];
		for (int i = 0; i != k; i++) {
			help[i] = input[i];
			insertHeap(help, i);
		}
		for (int i = k; i != input.length; i++) {
			if (input[i] < help[0]) {
				help[0] = input[i];
				heapify(help, 0, k);
			}
		}
		for (int i = 0; i < help.length; i++) {
			res.add(help[i]);
		}
		return res;

	}

	public static void insertHeap(int[] arr, int index) {
		while (arr[index] > arr[(index - 1) / 2]) {
			swap(arr, index, (index - 1) / 2);
			index = (index - 1) / 2;
		}
	}

	public static void heapify(int[] arr, int index, int size) {
		int left = index * 2 + 1;
		while (left < size) {
			int largest = left + 1 < size && arr[left + 1] > arr[left] ? left + 1 : left;
			largest = arr[largest] > arr[index] ? largest : index;
			if (largest == index) {
				break;
			}
			swap(arr, index, largest);
			index = largest;
			left = index * 2 + 1;
		}
	}

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

你可能感兴趣的:(剑指offer)