정수 n과 정수 3개가 담긴 리스트 slicer 그리고 정수 여러 개가 담긴 리스트 num_list가 주어집니다. slicer에 담긴 정수를 차례대로 a, b, c라고 할 때, n에 따라 다음과 같이 num_list를 슬라이싱 하려고 합니다. n = 1 : num_list의 0번 인덱스부터 b번 인덱스까지 n = 2 : num_list의 a번 인덱스부터 마지막 인덱스까지 n = 3 : num_list의 a번 인덱스부터 b번 인덱스까지 n = 4 : num_list의 a번 인덱스부터 b번 인덱스까지 c 간격으로 올바르게 슬라이싱한 리스트를 return하도록 solution 함수를 완성해주세요.
제한사항 n 은 1, 2, 3, 4 중 하나입니다. slicer의 길이 = 3 slicer에 담긴 정수를 차례대로 a, b, c라고 할 때 0 ≤ a ≤ b ≤ num_list의 길이 - 1 1 ≤ c ≤ 3 5 ≤ num_list의 길이 ≤ 30 0 ≤ num_list의 원소 ≤ 100
class Solution {
public int[] solution(int n, int[] slicer, int[] num_list) {
if(n ==1 ) {
int[] answer = new int[slicer[1]+1];
for(int i=0; i<slicer[1]+1 ; i++){
answer[i]=num_list[i];
}
return answer;
}
if(n ==2 ){
int[] answer = new int[num_list.length-slicer[0]];
int j=0;
for(int i=slicer[0]; i<num_list.length;i++){
answer[j] =num_list[i];
j++;
}
return answer;
}
if(n == 3){
int[] answer =new int[slicer[1]-slicer[0]+1];
int j=0;
for(int i=slicer[0]; i<=slicer[1]; i++){
answer[j]=num_list[i];
j++;
}
return answer;
}
if(n==4){
int len=0;
int j=0;
len=(slicer[1]-slicer[0])/slicer[2]+1;
int[] answer = new int[len];
for(int i=1; i<=len;i++ ) {
answer[j]=num_list[slicer[0]+slicer[2]*j];
j++;
}
return answer;
}
return null;
}
}
n이 1~4 로 주어져서 그에 맞는 경우에 맞게 풀어주었다.
다른 풀이를 보니 switch 를 썼다.
이경우 switch 를 쓰는게 더 가독성이 좋아보였다.!!
'자바 알고리즘 문제' 카테고리의 다른 글
| 왼쪽 오른쪽 (1) | 2024.05.01 |
|---|---|
| 잘라서 배열로 저장하기 (0) | 2024.04.30 |
| 가까운 수 (0) | 2024.04.28 |
| A로 B만들기 (1) | 2024.04.25 |
| 모스부호 (1) (0) | 2024.04.25 |