최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
반복문을 돌면서 지금 현재배열값과 같은 값을 가지는 경우엔 count+1을 해서 제일 큰 count값을 가져오는방식으로 하면 어떨까?
class Solution {
public int solution(int[] array) {
int answer = 0;
int mode = findMode(array);
return mode;
}
private static int findMode(int[] array){
int mode = 0;
int maxCount =0;
for(int i = 0 ; i < array.length ; i++){
int currentNum = array[i];
int currentCount = 1;
for(int j = i + 1 ; j < array.length ; j++){
if(currentNum == array[j]){
currentCount++;
}
}
if(currentCount > maxCount){
maxCount = currentCount;
mode = currentNum;
}
}
return mode;
}
}
최빈값이 여러개인 경우를 고려하지 않았다..!
문제 꼼꼼히 보기..