최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
0 < array의 길이 < 100
0 ≤ array의 원소 < 1000
같은 값 가지는 요소의 개수 세는 배열 만들어서 제일 큰 값 가지는 배열의 그 값을 반환하고 같은 값 가지는 배열이 2개인경우에는 -1 반환하기
class Solution {
public int solution(int[] array) {
int answer = 0;
int[] count = new int[1001];
int max = 0;
for(int i = 1 ; i < array.length ; i++){
count[array[i]]++;
if(max < count[i]){
max = count[i];
answer = max;
}
}
int same = 0;
for(int j = 0 ; j <1000 ; j++){
if(max == count[j]) same++ ;
if(same > 1) answer = -1;
}
return answer;
}
}
범위설정에서 오류가 난건지 값들이 조금씩 벗어나네...
class Solution {
public int solution(int[] array) {
int answer = 0;
int[] count = new int[1000];
int max = 0;
for(int i = 0 ; i < array.length ; i++){
count[array[i]]++;
if(max < count[array[i]]){
max = count[array[i]];
answer = max;
}
}
int same = 0;
for(int j = 0 ; j <1000 ; j++){
if(max == count[j]) same++ ;
if(same > 1) answer = -1;
}
return answer;
}
}
코드 실행은 됐는데, 정확도가 떨어진다
ㅡ