题解 | #牛群中最受欢迎的牛#
牛群中最受欢迎的牛
https://www.nowcoder.com/practice/7e23c4fdbd484fd1811c1b0d3a1017d8
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param k int整型 * @return int整型一维数组 */ function most_popular_cows(nums, k) { // write code here let obj = {}; for (let n of nums) { if (obj[n]) { obj[n]++; } else { obj[n] = 1; } } let cows = Object.keys(obj).map(id => ({id, count: obj[id]})); cows.sort((a, b) => b.count - a.count); return cows.slice(0, k).map(cow => Number(cow.id)).sort((a, b) => a - b); } module.exports = { most_popular_cows: most_popular_cows, };