leetcode面试准备:Kth Largest Element in an Array
1 题目
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 [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
接口:int findKthLargest(int[] nums, int k)
2 思路
找出数组中第k大的元素。
分治的思想,利用partition的过程结果,第k的数,在排序后的len - k的位置。
3 代码
/**
* 偷懒的做法
*/
public int findKthLargest0(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
/**
* 分治的思想,利用partition的过程结果,第k的数,在排序后的len - k的位置。
*/
public int findKthLargest(int[] nums, int k) {
int len = nums.length;
int goal = len - k;
int left = 0, right = len - 1;
int index = partition(nums, left, right);
while (index != goal) {
if (index < goal) {
left = index + 1;
} else {
right = right - 1;
}
index = partition(nums, left, right);
}
return nums[goal];
}
private int partition(int[] a, int p, int r) {
int i = p - 1;
int x = a[r];
for (int j = p; j < r; j++) {
if (a[j] <= x) {
i++;
swap(a, i, j);
}
}
swap(a, i + 1, r);
return i + 1;
}
private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
4 总结
分治