문제 설명
최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
https://school.programmers.co.kr/learn/courses/30/lessons/120812?language=java
import java.util.*;
class Solution {
public int solution(int[] array) {
Map<Integer, Integer> data = new HashMap<>();
for(int a : array){
if(data.containsKey(a)){
data.put(a, data.get(a) + 1);
}else
data.put(a, 1);
}
int maxKey = Collections.max(data.entrySet(), (a, b) -> a.getValue() - b.getValue()).getKey();
int maxValue = data.get(maxKey);
int count = 0;
for(Map.Entry<Integer, Integer> a : data.entrySet()){
if(a.getValue() == maxValue) count++;
}
return count > 1 ? -1 : maxKey;
}
}
- 해시 맵 사용해서 맵에 값이 있으면 +1, 없으면 1로 넣는다.
- 최빈값의 키와 최빈값을 찾는다.
- 반복문을 통해 최빈값을 비교하여 카운트해준다.
- 카운트가 1이상이면 최빈값이 여러 개이므로 -1 리턴, 그렇지 않으면 최빈값의 키를 리턴.