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.
解题思路:快排nlogn,quick select 平均On
public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length < k) return Integer.MAX_VALUE;
quicksort(nums, 0, nums.length-1);
return nums[nums.length-k];
}
public void quicksort(int[] nums, int low, int high) {
if (low > high) return;
int i = low, j = high;
int mid = nums[(low + high) / 2];
while (i <= j) {
while (nums[i] < mid) i++;
while (nums[j] > mid) j--;
if (i <= j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
if (i < high) quicksort(nums, i, high);
if (j > low) quicksort(nums, low, j);
}
}
public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length < k) return Integer.MAX_VALUE;
return findKth(nums, 0, nums.length-1, nums.length-k);
}
public int findKth(int[] nums, int start, int end, int k) {
if (start > end) return Integer.MAX_VALUE;
int pivot = nums[end];
int left = start;
for (int i = start; i < end; i++) {
if(nums[i] <= pivot) swap(nums, left++, i);
}
swap(nums, left, end);
if (left == k) return nums[left];
else if (left < k) return findKth(nums, left+1, end, k);
else return findKth(nums, start, left-1, k);
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}