[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]
정수 리스트에서 첫 원소부터 n칸 간격으로 원소를 골라 순서대로 담은 리스트를 구하는 워밍업 문제.
[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]
1. 아이디어
정수 리스트 num_list의 0번 인덱스부터 시작해 인덱스를 n씩 늘려가며 만나는 원소를 순서대로 담으면 되는 문제다. 인덱스가 리스트의 끝을 벗어나면 멈춘다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = num_list의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
class Solution {
public int[] solution(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(Integer::intValue).toArray();
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list, int n) {
vector<int> v;
for (int i = 0; i < num_list.size(); i += n) {
v.push_back(num_list[i]);
}
return v;
}
1
2
def solution(num_list, n):
return num_list[::n]
This post is licensed under CC BY 4.0 by the author.