题解 | #最小的K个数#
最小的K个数
http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
top K 问题 大顶堆AC了,没什么难度
ArrayList<Integer> res = new ArrayList<>(); if (input.length == 0) return res; input = createBigHeap(input); for (int i = 0; i < k; i++) { res.add(input[i]); } return res; } public int[] createBigHeap(int[] nums) { //初始化并创建堆,主要想在索引0下找到数组最大值 int length = nums.length; for (int i = (length - 1) / 2; i >= 0; i--) { adjustBigHeap(nums, i, length); } for (int i = length - 1; i >= 0; i--) { swap(nums, 0, i); adjustBigHeap(nums, 0, i); } return nums; } //这里我递归调整了一下 public void adjustBigHeap(int[] nums, int parent, int length) { int pivt = nums[parent]; int lChild = 2 * parent + 1; if (lChild < length) { int rChild = lChild + 1; int max = lChild; if (rChild < length && nums[rChild] > nums[lChild]) max = rChild; if (pivt >= nums[max]) return; swap(nums, parent, max); adjustBigHeap(nums, max, length); } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }