leetcode 451. 根据字符出现频率排序
问题描述: 给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:
"tree"
输出:
"eert"
解释: 'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
示例 2:
输入:
"cccaaa"
输出:
"cccaaa"
解释: 'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。
思路: 用堆(大顶堆,因为每次取当前最大的值)+Map 来实现
/**
* @param {string} s
* @return {string}
*/
var frequencySort = function(s) {
let map=new Map();
for(let i of s){
map.set(i,(map.get(i)||0)+1)
}
// console.log(map)
let heap=new Heap((a,b)=>map.get(a)>map.get(b));
for(let ley of map.keys()){
heap.push(ley)
}
let res='';
for(let i of map.keys()){
let item=heap.pop();
for(let j=0;j<map.get(item);j++){
res+=item;
}
}
return res;
};
//堆的实现
class Heap {
constructor(cmp) {
this.data = [];
this.cmp = cmp;
}
get size() {
return this.data.length;
}
get top() {
return this.data[0];
}
getData() {
return this.data;
}
swap(i, j) {
[this.data[i], this.data[j]] = [this.data[j], this.data[i]];
}
// 向上冒泡
up(i) {
let index=this.data.length-1;
while(index>0){
let p=Math.floor((index-1)/2);
if(p>=0&&this.cmp(this.data[index],this.data[p])){
this.swap(index,p);
index=p;
}else{
break;
}
}
}
// 下沉操作
down(i) {
if(this.data.length<2)return;
let index=0,l=2*index+1,len=this.data.length;
while(l<len){
let r=l+1;
if(r<len&&this.cmp(this.data[r], this.data[l]))l=r;
if(this.cmp(this.data[index], this.data[l]))break;
this.swap(index,l)
index=l;
l=index*2+1;
}
}
push(item) {
this.data.push(item);
this.up();
}
//删除堆顶元素
pop() {
this.swap(0, this.data.length - 1);
const res = this.data.pop();//已删除的元素(原来的堆顶元素)
this.down();
return res;
}
}