문제 설명
정수
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 | slicer | num_list | result |
3 | [1, 5, 2] | [1, 2, 3, 4, 5, 6, 7, 8, 9] | [2, 3, 4, 5, 6] |
4 | [1, 5, 2] | [1, 2, 3, 4, 5, 6, 7, 8, 9] | [2, 4, 6] |
입출력 예 설명
입출력 예 #1
- [1, 2, 3, 4, 5, 6, 7, 8, 9]에서 1번 인덱스부터 5번 인덱스까지 자른 리스트는 [2, 3, 4, 5, 6]입니다.
입출력 예 #2
- [1, 2, 3, 4, 5, 6, 7, 8, 9]에서 1번 인덱스부터 5번 인덱스까지 2개 간격으로 자른 리스트는 [2, 4, 6]입니다.
코드
import java.util.stream.IntStream;
class Solution {
public int[] solution(int n, int[] slicer, int[] num_list) {
int[] result;
int a = slicer[0];
int b = slicer[1];
int c = slicer[2];
if(n == 1) {
result = IntStream.range(0, b+1).map(i -> num_list[i]).toArray();
} else if(n == 2) {
result = IntStream.range(a, num_list.length).map(i -> num_list[i]).toArray();
} else if(n == 3) {
result = IntStream.range(a, b+1).map(i -> num_list[i]).toArray();
} else {
result = IntStream.iterate(a, i -> i <= b, i -> i + c).map(i -> num_list[i]).toArray();
}
return result;
}
}

int배열 사용
class Solution {
public int[] solution(int n, int[] slicer, int[] num_list) {
int[] result;
int a = slicer[0];
int b = slicer[1];
int c = slicer[2];
if(n == 1) {
result = new int[b+1];
for(int i = 0; i <= b; i++) {
result[i] = num_list[i];
}
} else if(n == 2) {
result = new int[num_list.length-a];
for(int i = a, j = 0; i < num_list.length; i++, j++) {
result[j] = num_list[i];
}
} else if(n == 3) {
result = new int[b-a+1];
for(int i = a, j = 0; i <= b; i++, j++) {
result[j] = num_list[i];
}
} else {
result = new int[((b-a)/2)+1];
for(int i = a, j = 0; i <= b; i=i+c, j++) {
result[j] = num_list[i];
}
}
return result;
}
}

Share article