๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ”ฅ PS(Problem Solving) ๐Ÿ”ฅ/programmers

[programmers] ์ •๋ ฌ, k๋ฒˆ์งธ์ˆ˜

by dar0m! 2020. 7. 16.
 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - 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๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด 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 ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

ํ•ด๊ฒฐ

key point, ์ •๋ ฌ!
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;

    int idx = 0;
    while(idx < commands.size()){
        vector<int> cut;
        for(int i = commands[idx][0] - 1; i < commands[idx][1]; i++){
            cut.push_back(array[i]);
        }
        sort(cut.begin(), cut.end());
        answer.push_back(cut[commands[idx++][2] - 1]);
    }
    return answer;
}

์ฒ˜์Œ์—๋Š” ์œ„์— ๋ณด์ด๋Š” ์ฝ”๋“œ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•˜์˜€๋Š”๋ฐ, ๋งž์€ ์‚ฌ๋žŒ๋“ค์˜ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ sort๋‚ด์—์„œ๋„ ๋‹ค์–‘ํ•œ ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅํ–ˆ๊ณ  ์‹œ์ž‘์ง€์ ๊ณผ ๋์ง€์ ์„ ์ง€์ •ํ•˜์—ฌ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅํ•˜์—ฌ ์•„๋ž˜ '์ฝ”๋“œ'์— ๋ณด์ด๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค.

๋กœ์ง์€ ๋˜‘๊ฐ™๋‹ค. i๋ฒˆ์งธ๋ถ€ํ„ฐ j๋ฒˆ์งธ๊นŒ์ง€ ์›์†Œ๋“ค์„ ์ž„์‹œ๋ฐฐ์—ด์— ์ €์žฅํ•˜๊ณ , ์ •๋ ฌํ•œ ๋’ค k๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ฐพ์•„์„œ answer๋ฐฐ์—ด์— ์ €์žฅํ•œ๋‹ค. ์ด ๋ฐฉ์‹์„ commands.size()๋งŒํผ ๋ฐ˜๋ณตํ•œ ํ›„ answer๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด ๋.

 

์ฝ”๋“œ

 

๋Œ“๊ธ€