Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given
Given
[3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
You may assume k is always valid, 1 ≤ k ≤ array's length.
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k);
for (int n : nums) {
queue.offer(n);
if (queue.size() > k) {
queue.poll();
}
}
return queue.poll();
}
}
=======
public class Solution {
private int partition(int[] nums, int from, int to) {
java.util.Random r = new java.util.Random();
int idx = from + r.nextInt(to - from + 1);
swap(nums, idx, to);
int start = from;
for (int i = from; i < to; i++) {
if (nums[i] < nums[to]) {
swap(nums, start, i);
start++;
}
}
swap(nums, to, start);
return start;
}
private void swap(int nums[], int p, int q) {
int tmp = nums[p];
nums[p] = nums[q];
nums[q] = tmp;
}
private int quickSelect(int[] nums, int k) {
int s = 0;
int e = nums.length - 1;
while (s <= e) {
int m = partition(nums, s, e);
if (m == k) {
return nums[m];
} else if (m < k) {
s = m + 1;
} else {
e = m - 1;
}
}
return 0;
}
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, nums.length - k);
}
}
没有评论:
发表评论