// Approach 2: PartitionclassSolution{publicint[]getLeastNumbers(int[] arr,int k){if(arr == null || arr.length ==0|| k <0)thrownewRuntimeException("Invalid input!");if(k ==0)returnnewint[]{};int lo =0;int hi = arr.length -1;int index =partition(arr, lo, hi);while(index != k -1){if(index < k -1){
lo = index +1;
index =partition(arr, lo, hi);}else{
hi = index -1;
index =partition(arr, lo, hi);}}int[] res =newint[k];for(int i =0; i < k; i++)
res[i]= arr[i];return res;}publicintpartition(int[] arr,int lo,int hi){int i = lo;int j = hi +1;int base = arr[lo];while(true){while(i < hi && arr[++i]< base)if(i == hi)break;while(j > lo && arr[--j]> base)if(j == lo)break;if(i >= j)break;swap(arr, i, j);}swap(arr, lo, j);return j;}publicvoidswap(int[] arr,int index1,int index2){int temp = arr[index1];
arr[index1]= arr[index2];
arr[index2]= temp;}}
2. Summary
Partition 函数:快速排序算法的一部分,可用于求解数组中第 n 大的数;应掌握该函数
时间复杂度:O(n);
空间复杂度:O(logn);
基于堆的算法:最小堆、最大堆;
适用范围:从海量数据中找出最小或最大的 k 个数,考虑到内存大小有限,因此无法将所有数据全部读入内存;