[LeetCode] Most Frequent Even Element

아르당·2026년 9월 6일

LeetCode

목록 보기
510/559
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 nums가 주어지고, 가장 빈번하게 나타나는 짝수 요소를 반환해라.
동률이면 가장 작은 값을 반환해라. 이런 요소가 없다면 -1을 반환해라.

Example

#1
Input: nums = [0, 1, 2, 2, 4, 4, 1]
Output: 2
Explanation:
짝수 요소는 0, 2, 4이다. 2와 4가 가장 빈번하게 나타난다.
가장 작은 2를 반환한다.

#2
Input: nums = [4, 4, 4, 9, 2, 4]
Output: 4
Explanation: 4는 가장 빈번하게 나타나는 짝수 요소이다.

#3
Input: nums = [29, 47, 21, 41, 13, 37, 25, 7]
Output: -1
Explanation: 짝수 요소가 없다.

Constraints

  • 1 <= nums.length <= 2000
  • 0 <= nums[i] <= 10^5

Solved

class Solution {
    public int mostFrequentEven(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int result = -1;
        int max = 0;

        for(int num : nums){
            if(num % 2 != 0){
                continue;
            }

            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);

            if(count > max || (count == max && num < result)){
                max = count;
                result = num;
            }
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글