λ¬Έμ
νμ΄ κ³Όμ
λ°°μ΄μμ κ°μ₯ λ§μ΄ λ±μ₯νλ k
κ°μ μ«μλ₯Ό μ°Ύμ λ°ννλ λ¬Έμ μ
λλ€.
μκ³ λ¦¬μ¦μ μκ° λ³΅μ‘λλ₯Ό O(NlogN)
μΌλ‘ μ§μ ν΄λ¨κΈ° λλ¬Έμ Hash Map
μ μ¬μ©ν΄μ λΉλμλ₯Ό μ μ₯νμμ΅λλ€.
μ°μ λ°°μ΄μ κ° μμλ₯Ό μννλ©° Map
μ λΉλμλ₯Ό μ μ₯νλλ°μλ O(N)
μ μκ° λ³΅μ‘λκ° λ€κ³ ,
μ΄ν λΉλμλ₯Ό κΈ°μ€μΌλ‘ Map
μ μ λ ¬νλ©΄ O(NlogN)
μ μκ° λ³΅μ‘λλ₯Ό μ»κ² λ©λλ€.
λ§μ§λ§μΌλ‘ μ λ ¬ κ²°κ³Ό k
κ°μ μμ μμλ€μ λ°νν΄μ£Όλ©΄ λ©λλ€.
μ½λ
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function (nums, k) {
const numberCount = new Map();
nums.forEach((num) => {
if (numberCount.has(num)) {
numberCount.set(num, numberCount.get(num) + 1);
} else {
numberCount.set(num, 1);
}
});
const sorted = [...numberCount.entries()].sort((a, b) => b[1] - a[1]);
const answer = [];
for (let i = 0; i < k; i++) {
answer.push(sorted[i][0]);
}
return answer;
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 114 - Flatten Binary Tree to Linked List (Medium) (0) | 2021.03.03 |
---|---|
LeetCode 287 - Find the Duplicate Number (Medium) (0) | 2021.03.03 |
LeetCode 322 - Coin Change (Medium) (0) | 2021.03.03 |
LeetCode 46 - Permutations (Medium) (0) | 2021.03.03 |
LeetCode 21 - Merge Two Sorted Lists (Easy) (0) | 2021.03.02 |
π¬ λκΈ