思路;
利用一个长度为k的数组,
遍历要查询的数组,如果辅助数组的长度小于k ,则直接添加到辅助数组
否则则跳过
c++实现如下
void findkmax(int* arr,int len,int k){ if(arr == NULL || len < k || len <= 0 ){ return; } multiset<int> set; for (int j = 0; j < len; ++j) { if(set.size() < k){ set.insert(arr[j]); } else{ multiset<int,greater<int>>::iterator it = set.begin(); int first = *it; if(first < arr[j]){ set.erase(it); set.insert(arr[j]); } } } for (multiset<int,greater<int>>::iterator it = set.begin(); it != set.end() ; ++it) { cout<<*it<<" "; } cout<<endl; }
java 版
public class Client { public static void main(String[] args) { int[] arr={6,1,3,4,4,0,87,45,3,90,90,90}; findKMax(arr,4); } private static void findKMax(int[] arr, int k) { if(arr == null || arr.length < k){ return; } int[] resultArr = new int[k]; int resultIndex = 0; boolean isSort = false; for (int i : arr) { if(resultIndex < k){ resultArr[resultIndex] = i; resultIndex++; }else { if(!isSort){ mergeSort(resultArr,0,resultArr.length - 1); isSort = true; } int first = resultArr[0]; if(first < i){ resultArr[0] = i; sortArr(resultArr); } } } for (int i : resultArr) { System.out.println(i); } } private static void sortArr(int[] arr){ for (int i = 1; i < arr.length; i++) { if(arr[0] <= arr[i]){// 这个位置上的数比第一个大,就把第一个数跟i-1 位置上的数进行交换 if(arr[0] == arr[i-1]){ return; } int temp = arr[0]; for (int j = 0; j < i - 1; j++) { arr[j] = arr[j + 1]; } arr[i-1] = temp; return; } if(i == arr.length - 1){ int temp = arr[0]; for (int j = 0; j < arr.length - 1; j++) { arr[j] = arr[j + 1]; } arr[i] = temp; } } } private static void mergeSort(int[] arr,int start,int end){ if(start >= end){ return; } int mid = (start + end) >> 1; mergeSort(arr,start,mid); mergeSort(arr,mid + 1, end); merge(arr,start,mid,end); } private static void merge(int[] arr, int start, int mid, int end) { int[] temp = new int[end - start + 1]; int left = start; int right = mid + 1; int index = 0; while (left <= mid && right <= end){ if(arr[left] < arr[right]){ temp[index] = arr[left]; left++; }else { temp[index] = arr[right]; right++; } index++; } while (left <= mid){ temp[index] = arr[left]; left++; index++; } while (right <= end){ temp[index] = arr[right]; right++; index++; } for (int i = 0; i < temp.length; i++) { arr[start + i] = temp[i]; } } }