[C++] 프로그래머스 뒤에서 5등까지

문제설명

정수로 이루어진 리스트 num_list가 주어집니다.
num_list에서 가장 작은 5개의 수를 오름차순으로 담은 리스트를
return하도록 solution 함수를 완성해주세요.


제한사항

• 6 ≤ num_list의 길이 ≤ 30
• 1 ≤ num_list의 원소 ≤ 100


입출력 예

num_list result
[12, 4, 15, 46, 38, 1, 14] [1, 4, 12, 14, 15]


풀이

num_list에서 가장 작은 5개의 수를 오름차순으로 담은 리스트를 만드는 구현 문제입니다. sort함수를 이용하여 오름차순으로 정렬한 뒤 5개 원소를 담은 리스트를 만들어 문제를 풀 수 있었습니다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> num_list) {
    vector<int> answer;
    vector<int> tmp = num_list;
    
    sort(tmp.begin(), tmp.end());
    
    for(int i = 0; i < 5; i++)
    {
        answer.push_back(tmp[i]);
    }
    
    return answer;
}


결과

코드 실행결과

Categories:

Updated:

Leave a comment