Skip to content

Instantly share code, notes, and snippets.

@tin80122
Created March 13, 2021 01:49
Show Gist options
  • Save tin80122/05ac997c564a072ade999237f84d7ff2 to your computer and use it in GitHub Desktop.
Save tin80122/05ac997c564a072ade999237f84d7ff2 to your computer and use it in GitHub Desktop.
CodePen Home LeetCode 347 bucket sort
var topKFrequent = function(nums, k) {
let hash = {}
nums.forEach(row => {
if(hash[row] === undefined) {
hash[row] = 1;
}else {
hash[row] += 1;
}
})
let res = [...hash].sort((a,b) => a[1]-b[1])
//object can't iterator directory
console.log(res)
};
var topKFrequent2 = function(nums, k) {
let hash = new Map();
nums.forEach(row => {
if(hash.has(row)) {
hash.set(row,hash.get(row)+1);
}else {
hash.set(row,1);
}
})
console.log('hash key sort:');
for (var key of hash.keys()) {
console.log(key);
}
let res = [...hash].sort((a,b) => b[1]-a[1])
res = res.map(item => item[0])
return res.slice(0,k)
};
const nums = [1,1,1,2,2,4], k = 2
console.log(topKFrequent2(nums,k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment