堆排序
void heapify(vector<int>& nums,int n, int i)
{
int largest = i;
int lson = 2*i+1;
int rson = 2*i+2;
if(lson<n && nums[largest]<nums[lson]) {
largest = lson;
}
if(rson<n && nums[largest]<nums[rson]) {
largest = rson;
}
if(largest!=i)
{
swap(nums[largest],nums[i]);
heapify(nums,n,largest);
}
}
int findKthLargest(vector<int>& nums, int k) {
for(int i = (nums.size()-1)/2; i>=0; i--)
heapify(nums,nums.size(), i);
for(int i =nums.size()-1;i >=0 ;i--)
{
swap(nums[0],nums[i]);
heapify(nums,i,0);
}
return nums[nums.size()-k];
}
堆+优先级
class Solution {
public:
static bool cmp(pair<int, int>& m, pair<int, int>& n) {
return m.second > n.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int>res;
unordered_map<int, int>map_num2count;
map_num2count.clear();
for (int i = 0; i < nums.size(); i++)
{
map_num2count[nums[i]]++;
}
priority_queue < pair<int, int>, vector<pair<int, int>>, decltype(&cmp)>q(cmp);
for (auto num2count: map_num2count){
if(q.size() < k)
q.push(num2count);
else{
if (q.top().second < num2count.second) {
q.pop();
q.push(num2count);
}
}
}
for (int x = 0; x < k; x++)
{
res.push_back(q.top().first);
q.pop();
}
return res;
}
};
快速排序
int patition(vector<int>& nums, int left, int right)
{
int pivot = left;
int i = left;
int j = right;
while (i < j) {
while (i < j && nums[j] >= nums[pivot])
{
j--;
}
while (i < j && nums[i] <= nums[pivot]) {
i++;
}
if (i < j)
swap(nums[i], nums[j]);
}
swap(nums[i], nums[pivot]);
return i;
}
void quicsort(vector<int>& nums,int left,int right)
{
if (left >= right) return;
int i = patition(nums, left, right);
quicsort(nums, left, i - 1);
quicsort(nums, i + 1, right);
}
int main(void)
{
vector<int> nums = { 10,7,8,11,5,7 };
quicsort(nums,0, nums.size()-1);
getchar();
return 0;
}