Topic
找到无序数组中最小的k 个数
Java code
Package com.lizhouwei.chapter8;/** * @Description: Find the smallest number of K in unordered array * @Author: Lizhouwei * @CreateDate: 2018/4/29 7:37 * @Mo Dify by: * @ModifyDate:*/public class Chapter8_4 {//Use heap sort time complexity to O (logn) public int[] Getkmin (int[] arr, int k) { if (k > Arr.length) {return new int[]{-1}; } int[] res = new INT[K]; for (int i = 0; i < K; i++) {res[i] = Arr[i]; Headinsert (res, i); } for (int i = k; i < arr.length; i++) {if (Arr[i] < res[0]) {res[0] = Arr[i]; Heapify (arr, 0, K); }} return res; }//heap initialization public void Headinsert (int[] arr, int index) {int parent = (index-1)/2; while (Index > 0) {if (Arr[parent] < Arr[index]) {swap (arr, parent, index); index = parent; } else {break; }}}//heap sort public void heapify (Int[] arr, int index, int heapsize) {int left = 2 * index + 1; int right = 2 * index + 2; int largest = index; while (left < heapsize) {if (Arr[left] > Arr[index]) {largest = left; } else if (right < heapsize && Arr[left] > Arr[right]) {largest = right; } else {break; } swap (arr, largest, index); index = largest; left = 2 * index + 1; right = 2 * index + 2; }} public void Swap (int[] arr, int a, int b) {int temp = Arr[a]; Arr[a] = arr[b]; ARR[B] = temp; }//test public static void main (string[] args) {chapter8_4 chapter = new Chapter8_4 (); Int[] arr = {1, 4, 7, 2, 3, 10, 9, 6, 5, 8}; int[] res = chapter.getkmin (arr, 5); System.out.print ("{1, 4, 7, 2, 3, 10, 9, 6, 5, 8} in the first five:"); for (int i = 0; i < res.length; i++) { System.out.print (res[i]+ ""); } }}
Results
Programmer's Code interview guide eighth array and matrix problems find the smallest number of K in an unordered array