Article directory
LeetCode Brushing Notes-Data Structure-day21
451. Sort by Character Frequency
1. Topic
Link to the original title: 451. Sorting according to the frequency of characters
2. Problem-solving ideas
Algorithm: Small Root Heap
Specific steps:
- We create a
pair<int,int>
small root heap for storage, which will bepair
sorted from small to large by the first position element pair
The first position stores the distance of all points from the origin (for convenience, the square of the distance is directly used here)pair
The second position of stores the subscript of the array where each point is located- After storing all the points in the heap, just take out the first k small elements in the heap, get their array coordinates, and put them into the final answer
3. Code
typedef pair<int,int> PII;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
vector<vector<int>> res;
priority_queue<PII, vector<PII>,greater<PII>> q;
for(int i=0;i<p.size();i++){
int t=p[i][0]*p[i][0]+p[i][1]*p[i][1];
q.push({
t,i});
}
while(k-->0){
auto t=q.top();
q.pop();
res.push_back(p[t.second]);
}
return res;
}
};
973. K Points Closest to Origin
1. Topic
Original title link: 973. K points closest to the origin
2. Problem-solving ideas
Algorithm: Big Root Heap
Specific steps:
- We create a
pair<int,int>
large root heap to store, andpair
the elements in the first position will be sorted from large to small pair
The first position of stores the number of occurrences of each characterpair
The second position stores the character itself- First use the hash table to count the number of occurrences of all characters, and then join the big root heap
- Finally, take out the big root heap elements and splice the string
3. Code
Method one:
typedef pair<int,int> PII;
class Solution {
public:
string frequencySort(string s) {
map<char,int> hash;
for(auto x:s) hash[x]++;
priority_queue<PII, vector<PII>> q;
for(auto [a,b]:hash) q.push({
b,a});
string res;
while(q.size()){
auto t=q.top();
q.pop();
res+=string(t.first,t.second);
}
return res;
}
};
Law 2:
class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int> cnt;
for(auto x:s) cnt[x]++;
sort(s.begin(),s.end(),[&](char a,char b){
if (cnt[a] != cnt[b]) return cnt[a] > cnt[b];
return a < b;
});
return s;
}
};