n개 간격의 원소들
정수 리스트 num_list와 정수 n이 주어질 때, num_list의 첫 번째 원소부터 마지막 원소까지 n개 간격으로 저장되어있는 원소들을 차례로 담은 리스트를 return하도록 solution 함수를 완성해주세요.
5 ≤ num_list의 길이 ≤ 20
1 ≤ num_list의 원소 ≤ 9
1 ≤ n ≤ 4
💻 풀이
j를 따로 선언해 주고Arrays.copyOf()를 사용해 j의 길이만큼 배열의 길이를 수정해 반환해주었다.⌛ 시간 0.02ms ~ 0.03ms
import java.util.*;
public int[] solution(int[] num_list, int n) {
int[] answer = new int[num_list.length];
int j = 0;
for(int i = 0; i < num_list.length; i += n) {
answer[j] = num_list[i];
j++;
}
return Arrays.copyOf(answer, j);
}
💻 풀이
num_list의 값을 n의 간격으로 List에 담아준다.stream() 과 mapToInt(i -> i) , toArray() 를 사용해 int 배열로 변환한 후 반환해 준다.⌛ 시간 1.83ms ~ 3.34ms
전체코드
import java.util.*;
public int[] solution1(int[] num_list, int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < num_list.length; i += n) {
list.add(num_list[i]);
}
return list.stream().mapToInt(i -> i).toArray();
}