ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [C++] K๋ฒˆ์งธ์ˆ˜
    ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต 2019. 9. 21. 19:47
    728x90

    ๋ฌธ์ œ ์„ค๋ช…

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

    ์ œํ•œ์‚ฌํ•ญ

    • 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์ž…๋‹ˆ๋‹ค.

     

    #include <string>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    	vector<int> answer;
    	vector<int> sorted_array;
    	int i, j, k;
    
    	for (int x = 0; x < commands.size(); ++x)
    	{
    		i = commands[x][0]-1;
    		j = commands[x][1]-1;
    		k = commands[x][2]-1;
    		for (int y = i; y <= j; ++y)
    		{
    			sorted_array.push_back(array.at(y));
    		}
    		sort(sorted_array.begin(), sorted_array.end());
    		answer.push_back(sorted_array.at(k));
    		sorted_array.clear();
    	}
    	return answer;
    }
    int main()
    {
    	vector<int> array = { 1, 5, 2, 6, 3, 7, 4 };
    	vector<vector<int>> commands;
    	vector<int> ans;
    	
    	vector<int> temp1 = { 2, 5, 3 };
    	vector<int> temp2 = { 4, 4, 1 };
    	vector<int> temp3 = { 1, 7, 3 };
    	commands.push_back(temp1);
    	commands.push_back(temp2);
    	commands.push_back(temp3);
    
    	ans = solution(array, commands);
    
    	for(int i=0;i<ans.size(); i++)
    		cout << ans[i] << endl;
    }
    728x90

    ๋Œ“๊ธ€

Designed by Tistory.