因为刚刚接触c++不是很久 在用的时候有些困难
然后今天在刷题的时候 遇到一个需要对哈希表排序的操作
然后研究了很长时间在
这里和大家分享一下
可以根据不同的要求 对于key和value来排序
里边需要用到pair的知识 这个方法可以用偷梁换柱来形容
我们就用vector<pair<int,int>>来代替map<int,int>
我们说的map中的key和value就用first和second来代替了
bool cmp1(pair<int, int> a, pair<int, int> b) {
return a.first < b.first;//对于first的升序
}
bool cmp2(pair<int, int>a, pair<int, int> b) {
return a.second < b.second;//对于second的升序
}
int main()
{
map<int, int> hash;
hash[1] = 4;
hash[3] = 3;
hash[2] = 5;
hash[4] = 1;
vector<pair<int, int>> vecs;
for (auto it = hash.begin();it!= hash.end();it++) {
vecs.push_back(make_pair(it->first, it->second));
}
//对于first升序排列
cout << "对于first升序排列:" << endl;
sort(vecs.begin(), vecs.end(),cmp1);
for (auto it = vecs.begin(); it != vecs.end(); it++)
cout << it->first << ':' << it->second << '\n';
//对于second升序排列
cout << "对于second升序排列:" << endl;
sort(vecs.begin(), vecs.end(), cmp2);
for (auto it = vecs.begin(); it != vecs.end(); it++)
cout << it->first << ':' << it->second << '\n';
return 0;
}
其实很好理解的
运行截图
案例
typedef pair<int, int> vecs;
vector<vecs>ans;
vector<int>res;
bool cmp(vecs a, vecs b) {
if (a.first != b.first)return a.first < b.first;//按1的个数
else return a.second < b.second;//如果1的个数相同 按原本顺序
}
vector<int> sortByBits(vector<int>& arr) {
for (auto e : arr)
{
int c = e;
int cnt = 0;
while (e) {
if (e % 2 == 1)cnt++;
e /= 2;
}
ans.push_back({ cnt,c });
}
sort(ans.begin(), ans.end(), cmp);
for (auto e : ans)res.push_back(e.second);
return res;
}
class Solution {
public:
static bool cmp(pair<int, int> a, pair<int, int> b) {
if (a.second == b.second) {
return a.first > b.first;
}
else {
return a.second < b.second;
}
}
vector<int> frequencySort(vector<int>& nums) {
map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
hash[nums[i]]++;
}
vector<pair<int, int>> vecs;
for (int i = 0; i < nums.size(); i++) {
vecs.push_back({ nums[i],hash[nums[i]] });
}
sort(vecs.begin(), vecs.end(), cmp);
vector<int> ans;
for (auto a : vecs) {
ans.push_back(a.first);
}
return ans;
}
};