λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 229 - Majority Element II (Medium)

by HandHand 2022. 2. 22.

πŸ’‘ 문제

LeetCode - 229번

🎯 풀이 κ³Όμ •

배열에 λ‹΄κΈ΄ μˆ«μžλ“€ μ€‘μ—μ„œ 일정 κΈ°μ€€κ°’ μ΄μƒμ˜ μˆ«μžλ“€μ„ μ°Ύμ•„μ„œ λ°˜ν™˜ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

배열에 λ‹΄κΈΈ 수 μžˆλŠ” 숫자의 λ²”μœ„κ°€ 크기 λ•Œλ¬Έμ— 해싱을 μ΄μš©ν•΄μ„œ μˆ«μžλ“€μ˜ 개수λ₯Ό μ„Έμ–΄μ€λ‹ˆλ‹€.

μ—¬κΈ°μ„œλŠ” 객체 λŒ€μ‹ μ— 읽고 μ“°λŠ” μ„±λŠ₯이 더 λ›°μ–΄λ‚œ Map 을 μ‚¬μš©ν–ˆμŠ΅λ‹ˆλ‹€.

πŸ‘¨‍πŸ’» μ½”λ“œ

var majorityElement = function (nums) {
  const numCount = new Map();
  const pivot = nums.length / 3;

  for (const num of nums) {
    if (numCount.has(num)) {
      const oldVal = numCount.get(num);
      numCount.set(num, oldVal + 1);
    } else {
      numCount.set(num, 1);
    }
  }

  const answer = [];
  for (const [key, value] of numCount) {
    if (value > pivot) {
      answer.push(key);
    }
  }

  return answer;
};
λ°˜μ‘ν˜•

'πŸƒ algorithm > leetcode' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

LeetCode 169 - Majority Element (Easy)  (2) 2023.02.05
LeetCode 733 - Flood Fill (Easy)  (0) 2022.03.07
LeetCode 300 - Longest Increasing Subsequence (Medium)  (0) 2021.06.14
LeetCode 36 - Valid Sudoku (Medium)  (0) 2021.04.13
LeetCode 120 - Triangle (Medium)  (0) 2021.04.13

πŸ’¬ λŒ“κΈ€