본문 바로가기
코딩테스트/프로그래머스 Lv0

[PCCE 기출문제] 창고정리

by kwh_coding 2024. 4. 3.

틀린 코드를 찾아내 1줄만 수정하여 정상 작동하도록 하는 문제

 

class Solution {
    public String solution(String[] storage, int[] num) {
        int num_item = 0;
        String[] clean_storage = new String[storage.length];
        int[] clean_num = new int[num.length];
        
        for(int i=0; i<storage.length; i++){
            int clean_idx = -1;
            for(int j=0; j<num_item; j++){
                if(storage[i].equals(clean_storage[j])){
                    clean_idx = j;
                    break;
                }
            }
            if(clean_idx == -1){
                clean_storage[num_item] = Integer.toString(num[i]);
                clean_num[num_item] = num[i];
                num_item += 1;
            }
            else{
                clean_num[clean_idx] += num[i];
            }
        }
        
        // 아래 코드에는 틀린 부분이 없습니다.
        
        int num_max = -1;
        String answer = "";
        for(int i=0; i<num_item; i++){
            if(clean_num[i] > num_max){
                num_max = clean_num[i];
                answer = clean_storage[i];
            }
        }
        return answer;
    }
}

주어진 코드는 이러했다. 


주어진 코드에서 주요 로직은 창고 정리이다. 정리를 위해 clean_storage와 clean_num 배열을 사용해서 같은 물건을 하나의 칸에 합친다. 물건의 갯수가 가장 많은 것을 찾기 위해 clean_num 배열을 확인해 보면 

clean_storage[num_item] = Integer.toString(num[i]);

clean_storage 배열에 물건의 갯수를 문자열로 저장하고 있다. 따라서 이 부분을

clean_storage[num_item] = storage[i];

변경하여 물건의 이름을 저장하여 물건의 갯수를 비교할 때 올바른 물건을 확인할 수 있도록 만들어준다.

 

 

 

 

 


출처: 프로그래머스 코딩 테스트 연습  https://programmers.co.kr/learn/challenges