5. Kth Largest Element (quick sort的变种)
https://www.lintcode.com/problem/kth-largest-element/description?_from=ladder&&fromId=1
public class Solution {
/**
* @param n: An integer
* @param nums: An array
* @return: the Kth largest element
*/
public int kthLargestElement(int n, int[] nums) {
// write your code here
quickSort(nums, 0, nums.length - 1);
int len = nums.length;
return nums[len - n];
} public void quickSort(int[] nums, int left, int right) {
if(left >= right) {
return;
}
int mid = nums[left + (right - left) / 2];
int l = left, r = right;
while(l <= r) {
while(l <= r && nums[l] < mid) {
l++;
}
while(l <= r && nums[r] > mid) {
r--;
}
if(l <= r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
quickSort(nums, left, r);
quickSort(nums, l, right);
}
}