ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 9/19 TIL [프로그래머스 코딩테스트] 최빈값 구하기
    프로그래밍/코딩테스트연습 2023. 9. 19. 20:27

    프로그래머스 코딩테스트 0단계  최빈값구하기

     

    사고의 흐름

    1. for문을 통해 앞뒤 값이 같으면 count하면 되지 않을까?

    2. 반복문을 돌리고 값이 다르면 count를 0으로 초기화해보자

    class Solution {
        public int solution(int[] array) {
            int answer = 0;
            
            int max=array[0];
            int count=0;
            for(int i=0; i<array.length; i++){
                if(array[i]>max){
                    max=array[i];
                }else if (array[i]==max){
                    count++;
                }
                
                if(count!=0 && array[i]>max){
                    count=0;
                
                                
            }
            answer=count;
            return answer;
        }
    }

    이렇게 짠 코드의 경우  최빈값이 중복되는 경우를 통과하지 못했다.

    아무리 생각해봐도 몇줄의 코드 추가로 문제를 해결할 방법이 생각나지 않아 이 코드는 폐기

     

    하지만 기본적인 포맷인 반복문을 통해 카운트하고 중복시 -1을 return해야 한다는 형식은 맞다고 생각했다

     

    class Solution {
        public int solution(int[] array) {
            int answer = 0;
    
            //제한사항 0 ≤ array의 원소 < 1000 를 사용
            //처음에 1000 무시하고 100넣었다가 런타임에러가 엄청나게 떴다.
            int m[]= new int[1000];			
            
            int count=0;
    
    		//배열이니 일반적인 반복문 대신 foreach 사용
            for(int a : array){
                m[a]++;
                if(m[a]>count){
                    count=m[a];
                    answer=a;
                }else if(m[a]==count){
                    answer=-1;
                }
            }
    
            return answer;
        }
    }

     

    해답은 숫자를 직접 카운트 하는 변수와 최빈값 변수를 따로 만들어 주는 것이었다

     

     

     

    나보다 잘한 다른 사람의 풀이

    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.ArrayList;
    import java.util.Arrays;
    
    class Solution {
        public int solution(int[] array) {
            List<Map.Entry<Integer, List<Integer>>> list = new ArrayList<>(Arrays.stream(array).boxed().collect(Collectors.groupingBy(o -> o)).entrySet()).stream().sorted((t0, t1) -> Integer.compare(t1.getValue().size(), t0.getValue().size())).collect(Collectors.toList());
            return list.size() > 1 && list.get(0).getValue().size() - list.get(1).getValue().size() == 0 ? -1 : list.get(0).getKey();
        }
    }

     

    아직도 이 풀이는 이해가 안간다. 어떻게 한거지

     

    다른 사람의 풀이를 보면 대부분이 map을 사용해서 풀었던데 아직 그 부분에 대한 공부가 부족함을 느낀다.

     

     

     

    그리고 정답률이 67%던데  0단계 수준이 맞나..?

    정석 배열부분 뒤적거리고 연습문제도 다시 풀어보면서  푸는데 한시간정도 걸린듯 

     

Designed by Tistory.