๋ฌธ์ ์ค๋ช
๋ฐฐ์ด array์ i๋ฒ์งธ ์ซ์๋ถํฐ j๋ฒ์งธ ์ซ์๊น์ง ์๋ฅด๊ณ ์ ๋ ฌํ์ ๋, k๋ฒ์งธ์ ์๋ ์๋ฅผ ๊ตฌํ๋ ค ํฉ๋๋ค.
์๋ฅผ ๋ค์ด array๊ฐ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด
- array์ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅด๋ฉด [5, 2, 6, 3]์ ๋๋ค.
- 1์์ ๋์จ ๋ฐฐ์ด์ ์ ๋ ฌํ๋ฉด [2, 3, 5, 6]์ ๋๋ค.
- 2์์ ๋์จ ๋ฐฐ์ด์ 3๋ฒ์งธ ์ซ์๋ 5์ ๋๋ค.
๋ฐฐ์ด array, [i, j, k]๋ฅผ ์์๋ก ๊ฐ์ง 2์ฐจ์ ๋ฐฐ์ด commands๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, commands์ ๋ชจ๋ ์์์ ๋ํด ์์ ์ค๋ช ํ ์ฐ์ฐ์ ์ ์ฉํ์ ๋ ๋์จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์ด์ ๋ด์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
- array์ ๊ธธ์ด๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
- array์ ๊ฐ ์์๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
- commands์ ๊ธธ์ด๋ 1 ์ด์ 50 ์ดํ์ ๋๋ค.
- commands์ ๊ฐ ์์๋ ๊ธธ์ด๊ฐ 3์ ๋๋ค.
์ ์ถ๋ ฅ ์
array | commands | return |
[1,5,2,6,3,7,4] | [[2,5,3], [4,4,1], [1,7,3] | [5,6,3] |
์ ์ถ๋ ฅ ์ ์ค๋ช
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅธ ํ ์ ๋ ฌํฉ๋๋ค. [2, 3, 5, 6]์ ์ธ ๋ฒ์งธ ์ซ์๋ 5์
๋๋ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 4๋ฒ์งธ๋ถํฐ 4๋ฒ์งธ๊น์ง ์๋ฅธ ํ ์ ๋ ฌํฉ๋๋ค. [6]์ ์ฒซ ๋ฒ์งธ ์ซ์๋ 6์
๋๋ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 1๋ฒ์งธ๋ถํฐ 7๋ฒ์งธ๊น์ง ์๋ฆ
๋๋ค. [1, 2, 3, 4, 5, 6, 7]์ ์ธ ๋ฒ์งธ ์ซ์๋ 3์
๋๋ค.
์ด ๋ฌธ์ ๋ ์๋ฅผ ๋ค์ด ๋ฐฐ์ด์ด [1,5,2,6,3,7,4] ์ผ ๋ i=2, j=5, k=3 ์ด๋ผ๋ฉด
๋ฐฐ์ด์ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅด๊ณ ([5,2,6,3])
์ด๊ฒ์ ์ ๋ ฌํ๋ฉด [2,3,5,6]์ด ๋๋๋ฐ
์ฌ๊ธฐ์ 3๋ฒ์งธ ์ซ์๋ 5๊ฐ ๋๋ค.
โ
๋ณดํต ๋ฐฐ์ด์ index๊ฐ 0๋ถํฐ ์์ํ๋๋ฐ ์ฌ๊ธฐ์๋ 1์ด๋ผ๊ณ ๊ฐ์ ํ๊ณ ํด์ผํ๋ค.
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
int num = commands.size();
for(int i=0;i<num;i++) {
vector<int> temp;
int idx = commands[i][0];
int idx2 = commands[i][1];
for(int j=idx;j<=idx2;j++) {
temp.push_back(array[j-1]);
}
int find = commands[i][2];
sort(temp.begin(), temp.end());
answer.push_back(temp[find-1]);
}
return answer;
}
์๋ ์ฝ๋๋ ๋ค๋ฅธ ์ฌ๋์ด ํผ ๋ค๋ฅธ ํ์ด์ธ๋ฐ ํจ์ฌ ๊ฐ๊ฒฐํ๊ณ ๊น๋ํ๊ธธ๋ ๊ฐ์ ธ์๋ดค๋ค.
์์ indexing์ ํ๋ฉด์ sort๋ฅผ ํ๊ณ ๊ณ์ฐํ๋๋ฐ
'๋ ์ ์ ๋ฐ ์๊ฐ์ ๋ชปํ์ง' ํ๋ ์๊ฐ์ด ๋ค์๋ค. (์ค๋๋ ๋๋ผ๋ ์๊ดด๊ฐ..)
#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;
}
https://programmers.co.kr/learn/courses/30/lessons/42748
โ