给定一个字符串数组,再给定整数 k ,请返回出现次数前k名的字符串和对应的次数。
返回的答案应该按字符串出现频率由高到低排序。如果不同的字符串有相同出现频率,按字典序排序。
对于两个字符串,大小关系取决于两个字符串从左到右第一个不同字符的 ASCII 值的大小关系。
比如"ah1x"小于"ahb","231"<”32“
字符仅包含数字和字母
数据范围:字符串数满足 ,每个字符串长度 ,
要求:空间复杂度 ,时间复杂度
["a","b","c","b"],2
[["b","2"],["a","1"]]
"b"出现了2次,记["b","2"],"a"与"c"各出现1次,但是a字典序在c前面,记["a","1"],最后返回[["b","2"],["a","1"]]
["123","123","231","32"],2
[["123","2"],["231","1"]]
"123"出现了2次,记["123","2"],"231"与"32"各出现1次,但是"231"字典序在"32"前面,记["231","1"],最后返回[["123","2"],["231","1"]]
["abcd","abcd","abcd","pwb2","abcd","pwb2","p12"],3
[["abcd","4"],["pwb2","2"],["p12","1"]]
function topKstrings( strings , k ) { const countMap = {}; for (let i = 0; i < strings.length; i++) { const str = strings[i]; const record = countMap[str] || (countMap[str] = [str, 0]); record[1] ++; } const countList = Object.values(countMap); countList.sort((i1, i2) => { const [s1, c1] = i1; const [s2, c2] = i2; return (c1 !== c2 ? c1 < c2 ? 1 : -1 : s1 < s2 ? -1 : 1 ); }); return countList.slice(0, k); }
/** * return topK string * @param strings string字符串一维数组 strings * @param k int整型 the k * @return string字符串二维数组 */ function topKstrings( strings , k ) { let map = new Map(); for(let i = 0; i < strings.length; i++){ if(map.has(strings[i])){ map.set(strings[i], (map.get(strings[i]) || 0) + 1) } else { map.set(strings[i], 1) } } let result = [...Array.from(map)].sort((a, b)=> { if(a[1] !== b[1]){ return b[1]-a[1]; } else { if(a[0] < b[0]){ return -1; } return 0 } }); return result.slice(0, k); } module.exports = { topKstrings : topKstrings };
function topKstrings( strings , k ) { // write code here strings.sort(); const map = strings.reduce((pre, cur) => { if (pre.has(cur)) pre.set(cur, pre.get(cur) + 1); else pre.set(cur, 1); return pre; }, new Map()); const res = []; map.forEach((val, key) => res.push([key, val])); res.sort((a, b) => b[1] - a[1]); return res.slice(0, k); }
function topKstrings( strings , k ) { // write code here strings.sort() let res = [] const map = new Map() for(let i=0; i<strings.length; i++){ if(!map.has(strings[i])){ map.set(strings[i], 1); }else{ map.set(strings[i], map.get(strings[i])+1); } } map.forEach((val, key) => { res.push([key, val]) }) res.sort((sec, fir) => { return fir[1] - sec[1] }) return res.slice(0,k) }