Post

[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]

[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]

문제 링크


1. 아이디어

정수 리스트 num_list의 0번 인덱스부터 시작해 인덱스를 n씩 늘려가며 만나는 원소를 순서대로 담으면 되는 문제다.


2. 복잡도

접근시간공간
풀이$O(M / N)$$O(M / N)$

($N$ = 입력값 n, $M$ = 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.