반응형
문제 링크 : https://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
문제 풀이
commands의 사이즈는 테스트 케이스의 수로 생각하여 for문을 통해 묶어주었다.
각 테스트 케이스에서 commands의 0번째 인덱스부터 1번째 인덱스까지의 배열을 answer에 넣고
STL sort를 이용하여 정렬 후 리턴할 ret 배열에 k번째 수(commands의 2번째 인덱스)를 넣는다.
단, 문제에서 말하는 k번째는 0번부터 시작이 아닌 1번부터 시작이므로 유의해야 한다.
코드
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> ret;
for(int t=0; t<commands.size(); t++){
vector<int> answer;
int cnt = commands[t][0];
while(true){
answer.push_back(array[cnt - 1]);
if(cnt == commands[t][1]) break;
else{
cnt++;
}
}
sort(answer.begin(), answer.end());
ret.push_back(answer[commands[t][2] - 1]);
}
return ret;
}
반응형
'Programming Solve > 프로그래머스' 카테고리의 다른 글
프로그래머스 위클리 챌린지 4주차 - 직업군 추천하기 / C++ (0) | 2021.09.23 |
---|---|
프로그래머스 - 위클리 챌린지 1주차, 부족한 금액 계산하기 / C++ (0) | 2021.09.07 |
프로그래머스 - 숫자 문자열과 영단어 / C++ (0) | 2021.08.07 |
프로그래머스 - 같은 숫자는 싫어 / C++ (0) | 2021.07.21 |
프로그래머스 - 이상한 문자 만들기 / C++ (0) | 2021.07.07 |