Post

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

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

문제 링크


1. 아이디어

정수 배열 numlist에서 정수 n의 배수가 아닌 수들을 제거한 배열을 return하는 문제로 모듈러 연산을 활용해 배수 여부를 판단해주면 된다.


2. 복잡도

시간복잡도공간복잡도
$O(N)$$O(1)$

N = numlist 길이


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int[] solution(int n, int[] numlist) {
        int cnt = 0;
        for (int x : numlist) {
            if (x % n == 0) cnt++;
        }

        int[] ans = new int[cnt];
        int idx = 0;
        for (int x : numlist) {
            if (x % n == 0) ans[idx++] = x;
        }

        return ans;
    }
}
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;
}

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