[C++] 프로그래머스 순서 바꾸기

문제설명

정수 리스트 num_list와 정수 n이 주어질 때,
num_list를 n 번째 원소 이후의 원소들과
n 번째까지의 원소들로 나눠 n 번째 원소 이후의 원소들을
n 번째까지의 원소들 앞에 붙인
리스트를 return하도록 solution 함수를 완성해주세요.


제한사항

• 2 ≤ num_list의 길이 ≤ 30
• 1 ≤ num_list의 원소 ≤ 9
• 1 ≤ n ≤ num_list의 길이


입출력 예

num_list n result
[2, 1, 6] 1 [1, 6, 2]
[5, 2, 1, 7, 5] 3 [7, 5, 5, 2, 1]


풀이

n 번째 원소 이후의 원소들을 리스트 앞에 위치하도록 코드를 작성하여 문제를 풀 수 있었습니다.

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> num_list, int n) {
    vector<int> answer;
    vector<int> l_arr;
    
    for(int i = 0; i < num_list.size(); i++)
    {
        if(i < n)
            l_arr.push_back(num_list[i]);
        else
            answer.push_back(num_list[i]);
    }
    
     answer.insert(answer.end(), l_arr.begin(), l_arr.end());
    
    return answer;
}


결과

코드 실행결과

Categories:

Updated:

Leave a comment