[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]
[Programmers] #181888 - n개 간격의 원소들 [Java][C++][Python]
1. 아이디어
$n$개 간격으로 저장된 원소는 인덱스가 $n$씩 차이 나는 원소이다. 예제에서 $n = 2$이면 인덱스 0, 2, 4의 원소가 답이므로, 인덱스 0부터 $n$씩 키우며 배열 끝을 넘기 전까지 고르면 된다.
2. 코드
풀이 [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.