Find the kth smallest number in an unsorted integer array.
Example
Example 1:
Input: [3, 4, 1, 2, 5], k = 3
Output: 3
Example 2:
Input: [1, 1, 1], k = 2
Output: 1
Challenge
An O(nlogn) algorithm is acceptable, if you can do it in O(n), that would be great.
思路:quick select,模板一定要写熟!
public class Solution {
/**
* @param k: An integer
* @param nums: An integer array
* @return: kth smallest element
*/
public int kthSmallest(int k, int[] nums) {
if(nums == null || nums.length == 0) {
return -1;
}
return findKth(nums, 0, nums.length - 1, k);
}
private int findKth(int[] A, int start, int end, int k) {
if(start == end) {
return A[start];
}
int mid = start + (end - start) / 2;
int pivot = A[mid];
int i = start, j = end;
while(i <= j) {
while(i <= j && A[i] < pivot) {
i++;
}
while(i <= j && A[j] > pivot) {
j--;
}
if(i <= j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
j--;
}
}
if(start + k - 1 <= j) {
return findKth(A, start, j, k);
}
if(start + k - 1 >= i) {
return findKth(A, i, end, k - (i - start));
}
return A[j + 1];
}
}