➰프로그래머스 : 최빈값 구하기

Digeut·2023년 3월 12일
0

프로그래머스

목록 보기
19/164

❔문제설명

최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 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;
    }
}

🙄오류

범위설정에서 오류가 난건지 값들이 조금씩 벗어나네...

틀린코드2

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

🙄오류2

코드 실행은 됐는데, 정확도가 떨어진다

💡코드풀이

profile
개발자가 될 거야!

0개의 댓글