lintcode题目
难度:中等
类型:分治
题意:求出数组第k小的数,可以使用优先队列,也可以使用快排。按照快排的思路,先寻找分割点,然后讲分割点两边的数据满足左边小于关键字,右边大于关键字,然后统计左边的数量left和k的相对大小,如果左边的数量比k大,说明第k小的数,一定在左边,所以直接求左边,反之在右边。
时间复杂度:堆
O
(
n
l
g
n
)
O(nlgn)
O(nlgn) 快排
O
(
n
)
O(n)
O(n)
class Solution {
public:
/**
* @param k: An integer
* @param nums: An integer array
* @return: kth smallest element
*/
int quick(int l, int r, vector<int>& nums, int k){
if(l == r) return nums[l];
int x = nums[l+r>>1];
int i = l-1, j = r+1;
while(i < j){
while(nums[++i] < x);
while(nums[--j] > x);
if(i < j) swap(nums[i], nums[j]);
}
int left = j - l + 1;
if(left >= k) return quick(l, j, nums, k);
else return quick(j+1, r, nums, k-left);
}
int kthSmallest(int k, vector<int> &nums) {
//快速排序
int l = 0, r = nums.size()-1;
return quick(l, r, nums, k);
}
};