桶排序算法
在leetcode中,桶排序经常被使用以对元素出现的频率进行排序。其过程为:
(1)频率统计:创建一个unordered_map,key为元素,value为出现次数。遍历所有元素,每遍历一个元素,该元素的value++,同时比较当前元素的value和当前最大的value,以得到最大出现次数n。
(2)桶的建立:根据最大出现次数n,创建有n+1个元素的vector(vector的下标是元素出现的次数),vector中的每个value也是一个vector,用于记录特定出现次数的元素。遍历(1)中创建的unordered_map,将元素放入对应的桶(出现次数)中。
(3)桶的遍历:逐个遍历所有桶(若找最少频率则从左向右,若找最大频率则从右向左),直到找到第k大/小出现频率的元素。
桶排序实现
下面通过通过两道leetcode题目展示桶排序的代码实现。
Leetcode347: 前K个高频元素
题目描述:
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
代码:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> counts;
int max_fre = 0;
for(auto &it: nums){
//计数并找最大,注意是++count
max_fre = max(max_fre, ++counts[it]);
}
vector<vector<int>> buckets(max_fre+1);
for(auto &it: counts){
//建立桶
buckets[it.second].push_back(it.first);
}
vector<int>res;
for(int i=buckets.size()-1; k>0&&i>=0; i--){
//从右往左遍历桶
for(auto &it: buckets[i]){
k--;
res.push_back(it);
}
}
return res;
}
};
Leetcode 451: 根据字符出现的频率排序
题目描述:
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。例如:输入"tree", 输出“eert"
代码:
class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int> counts;
int max_fre = 0;
//1. 统计频率
for(auto &it: s){
max_fre = max(max_fre, ++counts[it]);
}
//2.放入桶中
vector<vector<char>> buckets(max_fre+1);
for(auto &it: counts){
buckets[it.second].push_back(it.first);
}
//3.遍历桶并得到答案
string res;
for(int j=max_fre; j>0; j--){
for(auto &it : buckets[j]){
for(int i=0; i<j; i++) res += it;
}
}
return res;
}
};
总结:
这两道题都是桶排序,其过程都是先统计频率并计算最大出现频率,再建立桶,最后遍历桶并得出结果。唯一不同的地方是第一道题要求找前K个元素,而第二道题要求降序排序所有元素,在遍历桶的时候添加不同的约束条件即可。