Post

[Programmers] #12910 - 나누어 떨어지는 숫자 배열 [Java][C++][Python]

[Programmers] #12910 - 나누어 떨어지는 숫자 배열 [Java][C++][Python]

문제 링크


1. 아이디어

array의 각 원소에 대해 divisor로 나누어 떨어지는 수만 모아서 오름차순으로 반환하는 간단한 문제다.


2. 복잡도

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

($N$ = arr의 길이)


3. 코드

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

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

class Solution {
    public int[] solution(int[] arr, int divisor) {
        int[] ans = Arrays.stream(arr).filter(x -> x % divisor == 0).sorted().toArray();
        if (ans.length == 0) return new int[]{-1};
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> arr, int divisor) {
    vector<int> v;
    for (int x : arr) {
        if (x % divisor == 0) v.push_back(x);
    }
    sort(v.begin(), v.end());

    if (v.empty()) return {-1};
    return v;
}
1
2
3
def solution(arr, divisor):
    ans = sorted(x for x in arr if x % divisor == 0)
    return ans if ans else [-1]

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