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

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;
}
}
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;
}
}