[문제]
창고를 정리할 방법을 고민하던 선빈이는 같은 물건이 여러 칸에 나누어 들어있는 것을 발견하고 우선 같은 물건끼리 최대한 겹쳐쌓는 방식으로 창고를 정리하기로 했습니다. 선빈이의 창고에 들어있는 물건의 이름과 개수는 리스트 형태로 주어지며, 한 칸에 겹쳐질 수 있는 물건의 개수에는 제한이 없다고 가정합니다.
예를 들어 창고의 각 칸에 담겨있는 물건의 이름이storage = ["pencil", "pencil", "pencil", "book"],
각 물건의 개수가 num = [2, 4, 3, 1]이라면 연필과 책을 한 칸에 각각 겹쳐 쌓아 간단하게
clean_storage = ["pencil", "book"], clean_num = [9, 1]로 만들 수 있습니다.
주어진 solution 함수는 정리되기 전 창고의 물건 이름이 담긴 문자열 리스트 storage와 각 물건의 개수가 담긴 정수 리스트 num이 주어질 때, 정리된 창고에서 개수가 가장 많은 물건의 이름을 return 하는 함수입니다.
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;
}
}
출력하면 가장 많은 갯수를 가지고있는 문자열이 아닌 가장 많은 갯수가 출력이 됨
[답]
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] = storage[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;
}
}
'Coding Practice > 프로그래머스 Lv.0' 카테고리의 다른 글
특수문자 출력하기 (0) | 2024.01.18 |
---|---|
대소문자 바꿔서 출력 (0) | 2024.01.18 |
가습기 (0) | 2023.12.20 |
가채점 (1) | 2023.12.20 |
피타고라스의 정리 (0) | 2023.12.11 |