我想编写一个方法,以O(n + klogn)返回K个最大元素。下面的代码可以完成工作,但是时间复杂度不高。我该怎么做才能满足O(n + klogn)?
注意:每个单词都有自己的单词和频率。例如[Apple 25]。频率最高的单词最大。
public static Word[] heapSelect(Word[] array, int k){
Word [] words = new Word[k];
int n = array.length;
// Build heap (rearrange array)
for (int i = 0; i< n-1; i++) {
heapify(array, n, i);
for (int j = 0; j<n-i-1; j++)
{
if(array[j].compareTo(array[j+1]) < 0){
swap(array,j, j+1);
heapify(array, i, 0);
}
}
System.arraycopy(array, 0, words, 0, k);
}
return words;
}
我的heapify方法。
private static void heapify(Word[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l].compareTo(arr[largest])>0)
largest = l;
// If right child is larger than largest so far
if (r<n && arr[r].compareTo(arr[largest])>0)
largest = r;
// If largest is not root
if (largest != i)
{
swap(arr,i,largest);
heapify(arr, n, largest);
}
}