最小的k个数(无序)
最小的K个数
http://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf
import java.util.ArrayList; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> list = new ArrayList<Integer>(); int[] res = new int[k]; int temp; while (input == null || k<=0 || k > input.length) { return list; } for (int i = k / 2 - 1; i >= 0; i--) { adjustHeap(input, i, k-1); } for (int i = k; i < input.length; i++) { if (input[i] < input[0]) { input[0] = input[i]; adjustHeap(input, 0, k-1); } } for (int i = 0;i < k; i++) { list.add(input[i]); } return list; } public void adjustHeap(int []arr, int start, int end) { int temp = arr[start]; for (int child = start * 2 + 1; child <= end; child = child * 2 + 1) { if (child + 1 <= end && arr[child]<arr[child + 1]) { child++; } if (arr[child] < temp) { break; } arr[start] = arr[child]; start = child; } arr[start] = temp; } }
思路是:构造节点数为k的大顶堆维护数组最小的k个数,只要有数比堆内最大值(根节点)还小,就将根节点换出,同时调整大顶堆
若要有序的k个数,则需要将整个数组构建小顶堆,而后取出k个根节点组成最小k个数