一、数组中的第k个最大元素 难度:medium LeetCode题目号:215
题目描述:
思路:
本题目可使用快排或堆排,由于堆排有现成的数据结构(STL的priority_queue,即优先队列,内部由堆实现),实现起来很容易,故这里只谈一下快排的思路
假设数组中元素个数为n个,那么找第k大的元素就相当于找第n-k小的元素,由于快排的性质,每次划分后,比基准元素小的元素被划分到基准左边,比基准元素大的元素被划分到基准右边,故可将划分结果分为三种情况:
1)基准位置pos==k,说明基准就是第k小的元素,直接退出快排即可
2)基准位置pos<k,说明第k小的元素在基准的左边,只需在左边继续划分
3)基准位置pos>k,说明第k小的元素在基准的右边,只需在右边继续划分
代码如下:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int l = 0 , h = nums.size() - 1;
k = nums.size() - k;
while(l < h){
int pos = partition(nums, l , h);
if(pos == k){
break;
} else if (pos < k){
l = pos + 1;
} else{
h = pos - 1;
}
}
return nums[k];
}
int partition(vector<int>& nums, int i, int j){
int temp = nums[i];
while(i < j){
while( i < j && nums[j] > temp){
j--;
}
nums[i] = nums[j];
while( i < j && nums[i] <= temp){
i++;
}
nums[j] =nums[i];
}
nums[i] = temp;
return i;
}
};
时间复杂度:O(N) 空间复杂度:O(1)
二、出现频率最高的k个元素 难度:medium LeetCode题目号:347
题目描述:
思路:
用一个map去存数组中每个数出现的次数,map的键为数组中的元素,值为对应键出现的次数
然后利用一个最小堆去实现改算法,遍历map,当遍历到的元素出现次数比最小堆堆顶元素出现次数多时,弹出堆顶元素,将遍历到的元素压入最小堆,即遍历时分为以下两种情况:
1)最小堆中的元素个数小于k:直接将元素压入最小堆
2)最小堆中的元素个数等于k:判断所遍历到的元素出现次数是否比最小堆顶的元素出现次数多,若多,则替换
上述过程结束后,最小堆中存储的元素即为出现频率最高的k个元素
代码如下:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> Map;
for(int i : nums){
Map[i]++;
}
priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > > heap;
for(auto it : Map){
if(heap.size() == k){
if(it.second > heap.top().first){
heap.pop();
heap.push(make_pair(it.second, it.first));
}
}
else{
heap.push(make_pair(it.second, it.first));
}
}
vector<int> ans;
while(heap.size()){
ans.push_back(heap.top().second);
heap.pop();
}
return vector<int>(ans.begin(), ans.end());
}
};
三、根据字符出现频率排序 难度:medium LeetCode题目号:451
题目描述:
此题是上题的简化版,思路不再赘述
代码如下:
class Solution {
public:
string frequencySort(string s) {
map<char,int> Map;
for(char ch : s){
Map[ch]++;
}
priority_queue<pair<int,char> > heap;
for(auto it : Map){
heap.push(make_pair(it.second, it.first));
}
string ans = "";
while(heap.size()){
int num = heap.top().first;
char c = heap.top().second;
heap.pop();
while(num--){
ans += c;
}
}
return ans;
}
};