[프로그래머스/C++]Lv.1 - K번째 수

YH J·2023년 6월 4일
0

프로그래머스

목록 보기
113/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/42748

내 풀이

복사해올 범위를 복사해오는데 유의할점은 iterator로 가져오는건데
보통 전체 복사 해올때는 begin() 부터 end()까지 인데 end는 마지막 원소의 다음 위치이므로 begin()부분은 + index - 1을 하고 end()가 될 곳은 begin() + index 그대로 하면 된다.
구한 범위의 벡터를 정렬한 뒤 뽑아야 할 인덱스로 뽑아서 answer에 넣어준다.

내 코드

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    for(auto c : commands)
    {
        vector<int> vec(array.begin() + c[0] - 1, array.begin() + c[1]);
        sort(vec.begin(), vec.end());
        answer.push_back(vec[c[2] - 1]);
    }
    return answer;
}

다른 사람의 풀이

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

using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    vector<int> temp;

    for(int i = 0; i < commands.size(); i++) {
        temp = array;
        sort(temp.begin() + commands[i][0] - 1, temp.begin() + commands[i][1]);
        answer.push_back(temp[commands[i][0] + commands[i][2]-2]);
    }

    return answer;
}

다른 사람의 풀이 해석

따로 복사해서 정렬하지 않고 그 부분만 정렬했다.

profile
게임 개발자 지망생

0개의 댓글