Title description
There is an array of integers. Please find the K-th largest number in the array according to the idea of quick sort.
Given an integer array a, given its size n and the K you are looking for (K is between 1 and n), please return the Kth largest number to ensure that the answer exists.
Example 1
enter
[1,3,5,2,2],5,3
return value
2
代码实现:
import java.util.*;
public class Solution {
public int findKth(int[] a, int n, int K) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int i = 0; i < K; i++) {
queue.add(a[i]);
}
for (int i = K; i< n; i++) {
if (a[i] > queue.peek()) {
queue.poll();
queue.add(a[i]);
}
}
return queue.poll();
}
}