Post

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

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

문제 링크


1. 아이디어

정수 n과 정수 배열 numlist가 주어질 때, numlist에서 n의 배수가 아닌 수들을 제거한 배열을 반환하는 문제로 numlist를 순회하며 n으로 나눈 나머지가 0인 원소만 순서대로 모아 반환하면 된다.


2. 복잡도

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

($N$ = numlist의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
import java.util.*;

class Solution {
    public int[] solution(int n, int[] numlist) {
        return Arrays.stream(numlist).filter(x -> x % n == 0).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.