[프로그래머스] 최빈값 구하기

사당동씩씩이·2024년 4월 11일

문제

난이도 : 입문
주어진 배열의 수를 세면 되는 문제다.

풀이

import java.util.*;
class Solution {
    public int solution(int[] array) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int i : array) {
            if (count.containsKey(i)){
                int before = count.get(i);
                count.put(i,before+1);
            } else {
                count.put(i, 1);
            }
        }
        
        //최대값 찾기
        int max = 0;
        int maxKey = 0;
        for (Integer key : count.keySet()){
            int nowCount = count.get(key);
            if (nowCount>max){
                max = nowCount;
                maxKey = key;
            }
        }
        
        //중복값 확인
        int duplicate = 0;
        for (Integer values : count.values()) {
            if (max==values) {
                duplicate++;
            }
        }
        int answer = 0;
        if (duplicate > 1) {
            answer = -1;
        } else {
            answer = maxKey;
        }
        
        return answer;
    }
}

코드개선

  1. containsKey -- > getOrDefault(key, defualtValue)로 변경하여 key에 맵핑된 값이 있다면 value를 가져오고, 없다면 기본값을 가져오도록 변경.
  2. loop 줄이기 처음 배열은 순회하면서 최대값과 중복여부를 체크하도록 변경
import java.util.*;
class Solution {
    public int solution(int[] array) {
        Map<Integer, Integer> countNumbers = new HashMap<>();
        int max = 0; //최대빈도
        int maxKey = 0; //최대빈도를 갖는 수
        for (int key : array) {
            int count = countNumbers.getOrDefault(key, 0) + 1;
            if (count>max) {
                max = count;
                maxKey = key;
            } else if (count == max) {
                maxKey = -1;                
            }
            countNumbers.put(key, count);             
        }
        return maxKey;
    }
}
profile
N잡러 대충 이것저것 해보며 대충 사는 중

0개의 댓글