题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
* return topK string
* @param strings string字符串一维数组 strings
* @param k int整型 the k
* @return string字符串二维数组
*/
function topKstrings( strings , k ) {
// write code here
let obj={}
let res=[]
strings.sort()
for(let i=0;i<strings.length;i++){
if(obj.hasOwnProperty(strings[i])){
obj[strings[i]]++;
}
else{
obj[strings[i]]=1
}
}
for(var key in obj){
let arr2=[]
arr2.push(key,obj[key])
res.push(arr2)
}
res.sort(function(a,b){
if(a[1]==b[1]){
if(a[0]<b[0])return-1
else return 1
}
else{return b[1]-a[1]}
})
res.splice(k)
return res
}
module.exports = {
topKstrings : topKstrings
};