내일도무사히 2021. 2. 3. 12:03

 

programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr


 

 

 

문제

 


 

내 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
 
using namespace std;
 
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    vector<int> sliced_array;
    
    // commands[i][0] == first index + 1;
    // commands[i][1] == second index + 1;
    // commands[i][2] == picking point + 1;
    for(int i = 0; i < commands.size(); ++i) {
        sliced_array = {};
        
        for(int j = commands[i][0- 1; j < commands[i][1]; j++) {
            sliced_array.push_back(array[j]);
        }
        sort(sliced_array.begin(), sliced_array.end());
        
        answer.push_back(sliced_array[commands[i][2]-1]);
    }
    return answer;
}
cs

 

commands가 이중 for문으로 주어졌기 때문에 

2중 for문 안에 들어가 있는 j의 값을 통해 input되어진 array를 슬라이스했고

그 뒤에 sort를 하여 답을 구해냈다.

 


 

다른 사람의 풀이

 

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;
    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;
}
cs

 

 

2중 for문의 슬라이싱 하는 부분을

sort 함수의 temp.begin() 인수에 command 값을 더해줬다.