GitHubSeob
C++ / 프로그래머스 / K번째수 본문
문제
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
문제풀이
array의 i번째 수부터 j번째 숫자까지 자르고, 자른 숫자를 오름차순으로 정렬하고 k번째 숫자를 return 하는 문제이다.
i는 commands의 행수만큼, 배열은 0부터 시작이므로 commands[i][0]-1부터 commands[i][1]-1까지 int형 벡터 number에 push 한다.
숫자를 i번째부터 j번째까지 잘랐으므로 sort로 오름차순으로 정렬한다.
정렬이 끝났으면 number의 commands[i][2]-1번째 수를 답에 push 한다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
for (int i = 0; i < commands.size(); ++i) {
vector<int>number;
for (int j = commands[i][0] - 1; j < commands[i][1]; ++j)
number.push_back(array[j]);
sort(number.begin(), number.end());
answer.push_back(number[commands[i][2] - 1]);
}
return answer;
}
'Programmers > Level 1' 카테고리의 다른 글
C++ / 프로그래머스 / 내적 (0) | 2021.08.15 |
---|---|
C++ / 프로그래머스 / 숫자 문자열과 영단어 (0) | 2021.08.15 |
C++ / 프로그래머스 / 위클리 챌린지 2주차 / 상호 평가 (0) | 2021.08.11 |
C++ / 프로그래머스 / 키패드 누르기 (2) | 2021.08.08 |
C++ / 프로그래머스 / 크레인 인형뽑기 게임 (0) | 2021.08.08 |