나누어 떨어지는 숫자 배열

김현민·2021년 3월 16일
0

Algorithm

목록 보기
40/126
post-thumbnail

문제

내 코드

#include <bits/stdc++.h>

using namespace std;

vector<int> solution(vector<int> arr, int divisor)
{
    vector<int> answer;
    vector<int>::iterator iter;

    for (iter = arr.begin(); iter != arr.end(); iter++)
    {

        if (*iter % divisor != 0)
        {
            // cout << *iter << endl;
            arr.erase(iter);
            iter--;
        }
    }
    if (arr.empty())
        arr.push_back(-1);
    else
        sort(arr.begin(), arr.end());
    for (iter = arr.begin(); iter != arr.end(); iter++)
    {
        answer.push_back(*iter);
    }

    return answer;
}
  • iterator 반복자를 이용해서 풀어봄

  • vector요소를 없애는 eraser함수를 사용했다.
    이 함수는 요소를 삭제함과 동시에 다음 요소를 지정하기 때문에, 그냥 지우면 한다리 건너뛰게 되므로 이를 방지하기 위해 iter--를 해줌.

  • 배열이 비어있으면 -1을 push_back() 해주고, 아니면 정렬한다.

profile
Jr. FE Dev

0개의 댓글