1 回答

TA貢獻1801條經驗 獲得超16個贊
這個問題的最佳情況是 O(nlogk),我們可以使用最大或最小堆數據結構來解決這個問題。如果 k 很小,這將接近 O(n)。這個想法是我們不必對整個數組進行排序,而是取一個大小為 k 的堆,并始終對堆中存在的 k 個元素進行排序。
O(n) 遍歷數組
O(logk) 用于使用堆排序對 k 個元素進行排序。
public Integer getKthEle(Integer[] numbers, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue(k, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return b-a;
}
}
);
for(int i=0;i<k;i++) {
maxHeap.offer(numbers[i]);
}
// maintain the size k by adding to the queue if the next element is smaller than the head of the queue; remove from the head of the queue which is the largest element in the queue
for(int i=k;i<numbers.length;i++) {
if(numbers[i] < maxHeap.peek()) {
maxHeap.offer(numbers[i]);
maxHeap.poll();
}
}
return maxHeap.peek();
}
添加回答
舉報