题目:快排
解法:递归
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
quicksort(nums, 0, nums.size()-1);
return nums;
}
void quicksort(vector<int>& nums, int start, int end) {
if (start >= end) return;
int p = partition(nums, start, end);
quicksort(nums, start, p - 1);
quicksort(nums, p + 1, end);
}
int partition(vector<int>& nums, int start, int end) {
int randindex = rand()%(end - start + 1) + start;
swap(nums[start], nums[randindex]);
int base = nums[start];
while(start < end) { // 不能取等,因为下面的while不能取等
while (start < end && nums[end] >= base) //第二个&&不能都不取等,否则出不了循环
end --;
nums[start] = nums[end];
while (start < end && nums[start] <= base)
start ++;
nums[end] = nums[start];
}
nums[start] = base;
return start;
}
};
解法:非递归写法
void quicksort(vector<int>& nums, int start, int end) {
if (start >= end) return;
int p = partition(nums, start, end);
stack<int> s;
if (p > start) {
s.push(start);
s.push(p - 1);
}
if (p < end) {
s.push(p + 1);
s.push(end);
}
while (!s.empty()) {
int r = s.top(); // 注意栈顺序是反的!
s.pop();
int l = s.top();
s.pop();
p = partition(nums, l, r);
if (p > l) {
s.push(l);
s.push(p - 1);
}
if (p < r) {
s.push(p + 1);
s.push(r);
}
}
}
复杂度
- 时间:O(nlogn)
- 空间:O(1)
题目:LC215求第K个大
解法:快排
class Solution {
public:
int ret;
int findKthLargest(vector<int>& nums, int k) {
quicksortk(nums, k, 0, nums.size() - 1);
return nums[nums.size() - k]; // 排好序了
}
void quicksortk(vector<int>& nums, int k, int start, int end) {
if (start >= end) return;
int p = partition(nums, start, end);
if (p == nums.size() - k) //排到了目标位置
return ;
else if (p > nums.size() - k)
quicksortk(nums, k, start, p - 1);
else
quicksortk(nums, k, p + 1, end);
}
int partition(vector<int>& nums, int start, int end) {
int randindex = rand()%(end - start + 1) + start;
int base = nums[randindex];
swap(nums[start], nums[randindex]);
while (start < end) {
while (start < end && nums[end] >= base) end--;
nums[start] = nums[end];
while (start < end && nums[start] <= base) start++;
nums[end] = nums[start];
}
nums[start] = base;
return start;
}
};
复杂度
- 时间:O(n)
- 空间:O(1)
解法:堆
维护大小为k的小根堆,遍历完top就是所求
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < nums.size(); ++ i) {
if (i < k) pq.push(nums[i]);
else {
if (nums[i] > pq.top()) {
pq.pop();
pq.push(nums[i]);
}
}
}
return pq.top();
}
复杂度
- 时间:O(nlogk)
- 空间:O(k)