Post

[Programmers] #120905 - n의 배수 고르기 [Java][C++][Python]

정수 배열 numlist에서 n의 배수만 남긴 배열을 반환하는 워밍업 문제.

[Programmers] #120905 - n의 배수 고르기 [Java][C++][Python]

문제 링크


1. 아이디어

numlist를 순회하며 n으로 나눈 나머지가 0인 원소만 순서대로 모아 반환하는 워밍업 문제다.


2. 복잡도

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

($N$ = numlist의 길이)


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 n, int[] numlist) {
        List<Integer> list = new ArrayList<>();
        for (int x : numlist) {
            if (x % n == 0) list.add(x);
        }

        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(int n, vector<int> numlist) {
    vector<int> v;
    for (int x : numlist) {
        if (x % n == 0) v.push_back(x);
    }

    return v;
}
1
2
def solution(n, numlist):
    return [x for x in numlist if x % n == 0]

This post is licensed under CC BY 4.0 by the author.