๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][์ •๋ ฌ] K๋ฒˆ์งธ ์ˆ˜

ibelieveinme 2023. 4. 19. 00:11
728x90

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ณ ๋“์  kit ์ •๋ ฌํŒŒํŠธ 1๋ฒˆ K๋ฒˆ์งธ ์ˆ˜

 

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

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

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ•ด๊ฒฐ๋ฒ•]

๋ฒกํ„ฐ์—์„œ i~j ์ˆซ์ž๋ฅผ ์ถ”์ถœํ•˜๊ณ  ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ ํ›„, k๋ฒˆ์งธ ์ˆ˜๋ฅผ ๋ฝ‘๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ˆœ์„œ๋Œ€๋กœ ์ฐจ๊ทผ์ฐจ๊ทผ ํ•˜๋‹ˆ๊นŒ ๊ธˆ๋ฐฉ ํ’€๋ ธ๋‹ค.

but ๋ฐฑ๋งŒ๋…„๋งŒ์— C++ ๋‹ค์‹œ ์žก์œผ๋‹ˆ ํ•จ์ˆ˜๊ฐ€ ํ—ท๊ฐˆ๋ฆฐ๋‹ค... ๊ฐ์žก์ž keep going...

 

[์•Œ์•„๋‘˜ ๊ฒƒ]

1. ๋ฒกํ„ฐ ๋ถ€๋ถ„์ถ”์ถœ

vector<int> partArray(array.begin() + beginIndex, array.begin() + endIndex);

2. ๋ฒกํ„ฐ ์ •๋ ฌ

sort(v.begin(), v.end()); // ๋ฒกํ„ฐ ์ „์ฒด๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ๋•Œ
sort(v.begin(), v.end(), greater<int>()); // ๋ฒกํ„ฐ ์ „์ฒด๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ๋•Œ

 

[์ฝ”๋“œ]

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    
    //๋ช…๋ น ๊ฐฏ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต
    for(int i = 0; i < commands.size(); i++){
        
        //๋ช…๋ น์–ด ๊ฐ’ ๋ณด๊ธฐ์ข‹๊ฒŒ ์„ ์–ธ
        int beginIndex = commands[i][0];
        int endIndex = commands[i][1];
        int answerIndex = commands[i][2];
        
        //beginInde ~ endIndex๊นŒ์ง€ ๊ฐ’ ์ถ”์ถœ
        vector<int> partArray(array.begin() + beginIndex - 1, array.begin() + endIndex);

        //์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
        sort(partArray.begin(), partArray.end());

        //K๋ฒˆ์งธ ์ˆ˜ ์ถ”์ถœ
        answer.push_back(partArray[answerIndex - 1]);
    }
    
    return answer;
}

์‹œ๊ฐ„๋ณต์žก๋„: for๋ฐ˜๋ณต๋ฌธ O(N) x ๋ฒกํ„ฐ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ Quick ์ •๋ ฌ O(NlogN) = O(N^2logN)

728x90