Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[C++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - "K๋ฒˆ์งธ ์ˆ˜" ํ’€์ด

meeeeejin 2020. 6. 2. 21:13

๋ฌธ์ œ ์„ค๋ช…

๋ฐฐ์—ด array์˜ i๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ j๋ฒˆ์งธ ์ˆซ์ž๊นŒ์ง€ ์ž๋ฅด๊ณ  ์ •๋ ฌํ–ˆ์„ ๋•Œ, k๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด array๊ฐ€ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด

  1. array์˜ 2๋ฒˆ์งธ๋ถ€ํ„ฐ 5๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฅด๋ฉด [5, 2, 6, 3]์ž…๋‹ˆ๋‹ค.

  2. 1์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•˜๋ฉด [2, 3, 5, 6]์ž…๋‹ˆ๋‹ค.

  3. 2์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์˜ 3๋ฒˆ์งธ ์ˆซ์ž๋Š” 5์ž…๋‹ˆ๋‹ค.

๋ฐฐ์—ด array, [i, j, k]๋ฅผ ์›์†Œ๋กœ ๊ฐ€์ง„ 2์ฐจ์› ๋ฐฐ์—ด commands๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, commands์˜ ๋ชจ๋“  ์›์†Œ์— ๋Œ€ํ•ด ์•ž์„œ ์„ค๋ช…ํ•œ ์—ฐ์‚ฐ์„ ์ ์šฉํ–ˆ์„ ๋•Œ ๋‚˜์˜จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

 

๋ฌธ์ œ ์ฃผ์†Œ: https://programmers.co.kr/learn/courses/30/lessons/42748

 

๋ฌธ์ œ ํ’€์ด

array๋ฅผ i๋ถ€ํ„ฐ j๊นŒ์ง€ ์ž๋ฅธ ๋ฐฐ์—ด์„ temp์— ์ €์žฅํ•˜๊ณ , temp๋ฅผ ์ •๋ ฌํ•œ ๋’ค์— k๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜๋ฅผ answer์— push ํ•˜๋ฉด ๋จ

 

 

์†Œ์Šค ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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> temp;
        temp.assign(array.begin() + commands[i][0- 1, array.begin() + commands[i][1]);
        sort(temp.begin(), temp.end());
        answer.push_back(temp[commands[i][2- 1]);
    }
 
    return answer;
}
cs
728x90