Algorithm - CodeKata #09 ๐Ÿ“Œ

Sangho Moonยท2020๋…„ 9์›” 12์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
16/37
post-thumbnail
post-custom-banner

1. Question

nums๋Š” ์ˆซ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
๊ฐ€์žฅ ์ž์ฃผ ๋“ฑ์žฅํ•œ ์ˆซ์ž๋ฅผ k ๊ฐœ์ˆ˜๋งŒํผ returnํ•ด์ฃผ์„ธ์š”.

  • nums = [1,1,1,2,2,3]
    k = 2

    return [1,2]

  • nums = [1]
    k = 1

    return [1]


2. Answer

function topK(nums, k) {
  let obj = {}
  for (let i in nums) {
    nums[i] in obj ? obj[nums[i]] += 1 : obj[nums[i]] = 1
  }

  let sorted = Object.keys(obj).sort(function(a, b) {
    return obj[b] - obj[a]
  })

  return sorted.slice(0, k).map(x => parseInt(x))
}

topK([1,1,1,1,2,2,3],2)
profile
Front-end developer

0๊ฐœ์˜ ๋Œ“๊ธ€