Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 750 Bytes

451. 根据字符出现频率排序.md

File metadata and controls

42 lines (33 loc) · 750 Bytes

思路

先用map存储key-count,然后再对count倒序排序再拼接

代码

var frequencySort = function(s) {
  let obj = buildTargetObject(s);
  const arr = getTargetSort(obj);
  return buildStr(arr)
};

function buildTargetObject(str) {
  const obj = {}
  for(let i = 0; i < str.length; i ++) {
    let cur = str[i];
    obj[cur] = (obj[cur] || 0) + 1
  }
  return obj
}

function getTargetSort(obj) {
  const arr = Object.entries(obj)
  return arr.sort((a, b) => b[1] - a[1])
}

function buildStr(arr) {
  let str = '';
  for(let i = 0; i < arr.length; i ++) {
    let [key, value] = arr[i]
    str += key.repeat(value)
  }
  return str
}

复杂度分析

时间复杂度 $O(NlogN)$

空间复杂度 $O(N)$