programmers.co.kr/learn/courses/30/lessons/42748
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
- 주어진 입력에서 split()와 같이 일정 부분의 원소들을 자르고 정렬 후 k 번째 수를 고르는 문제
더보기
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> arr, vector<vector<int>> commands) {
vector<int> answer;
const int commandsSize = commands.size();
for (int cmdIdx = 0; cmdIdx < commandsSize; cmdIdx++)
{
std::vector<int> slice;
const int startIdx = commands[cmdIdx][0] - 1;
const int endIdx = commands[cmdIdx][1] - 1;
const int k = commands[cmdIdx][2];
const int arrSize = arr.size();
for (int arrIdx = 0; arrIdx < arrSize; arrIdx++)
{
if (startIdx <= arrIdx && endIdx >= arrIdx)
{
slice.push_back(arr[arrIdx]);
}
}
sort(slice.begin(), slice.end());
answer.push_back(slice[k - 1]);
}
return answer;
}
int main()
{
// input
std::vector<int> arr = { 1,5,2,6,3,7,4 };
std::vector<int> cmd_1 = { 2,5,3 };
std::vector<int> cmd_2 = { 4,4,1 };
std::vector<int> cmd_3 = { 1,7,3 };
std::vector<std::vector<int>> commands;
commands.push_back(cmd_1);
commands.push_back(cmd_2);
commands.push_back(cmd_3);
solution(arr, commands);
return 0;
}
'Coding Problem > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Lv1] - 완주하지 못한 선수 (0) | 2021.04.24 |
---|---|
[프로그래머스/Lv1/카카오] - 신규 아이디 추천 (0) | 2021.04.20 |
[프로그래머스/Lv1/카카오] - 크레인 인형뽑기 (0) | 2021.04.19 |
[프로그래머스/Lv1/카카오] - 실패율 (0) | 2021.04.18 |
[프로그래머스/Lv1] - 문자열 내 p 와 y의 개수 (0) | 2021.04.18 |