Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

거인의 코딩일지

[Lv.0_Java] 최빈값 구하기 본문

알고리즘테스트/Programmers

[Lv.0_Java] 최빈값 구하기

코딩거인 2023. 8. 16. 10:21
728x90

import java.util.*;
class Solution {
    public int solution(int[] array) {
        Arrays.sort(array);
        int answer = 0;
        int maxNum = array[array.length-1];
        int [] cnt = new int [maxNum +1];
        
        for(int i = 0; i < array.length; i++){
            cnt[array[i]] ++;
        }
        int superMax = cnt[0];
        for(int i = 1; i < cnt.length; i++){
            if(superMax < cnt [i]){
                superMax = cnt[i];
                answer = i;
            }else if(superMax == cnt[i]){
                answer = -1;
            }
        }
        return answer;
    }
    
}

굉장히 어려웠따.... 

몇번 나왔는지 알아보기 위하여 cnt 라는 배열을 만들어주었다 인덱스를 활용해 주기위해서 배열의 길이는 maxNum +1 을 해주었고 빈도수를 카운트 해서 그 인덱스에 넣어주었다.

그 후 for 문을 통하여 superMax 라는 최빈값을 알아내었고 그 알아낸 값을 answer 에 대입해주었다

만약 superMax 와 카운트 배열에 있는 값이 동일하다면 answer 에 -1 을 대입해주었다.

 

728x90