제주 탈출 일지

[c++][python3] 프로그래머스 레벨 1 - K번째 수 본문

코딩 테스트

[c++][python3] 프로그래머스 레벨 1 - K번째 수

귀건 2020. 10. 26. 23:15
728x90
반응형

programmers.co.kr/learn/courses/30/lessons/42748?language=cpp

 

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

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

programmers.co.kr

이 문제에서 중요한 것은 이차원 벡터에서의 반복자의 값 접근이다.

이차원 벡터의 객체를 (*iter) 형태로 접근한 후에 []를 통해 그 객체 내부의 값에 접근한다.

*iter[]를 바로 쓰게 되면 에러가 나게 된다.

 

그리고 iter2 ~ iter3까지의 반복자 구간은 [begin, end)처럼 개구간으로 초기화되기 때문에 iter3의 값을 -1을 해주지 않았다.

 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> array, vector<vector<int>> commands) {
    vector<int> answer;
    
    vector<vector<int> >::iterator iter;
    for(iter = commands.begin(); iter != commands.end(); ++iter){
        //i-1 ~ j-1까지 sorting 후 k-1번째
        vector<int>::iterator iter2;
        vector<int>::iterator iter3;
        
        iter2 = array.begin() + (*iter)[0] - 1;
        iter3 = array.begin() + (*iter)[1];
        
        vector<int> temp(iter2,iter3);
        sort(temp.begin(), temp.end());
        answer.push_back(temp[(*iter)[2] - 1]);
    }
    
    
    return answer;
}

 

2021.06.08)

 

def solution(array, commands):
    answer = []
    
    for i in range(len(commands)):        
        tmp = array[commands[i][0]-1:commands[i][1]]
        tmp.sort()
        answer.append(tmp[commands[i][2]-1])
    
    return answer

파이썬 리스트 자르기 + 정렬로 해결했다.

다른 사람의 풀이에서 나온 한줄 코딩에 살짝 경악했는데, 잘 보니 어려운 코드는 아니더라ㅎ..

보다보니 그래도 조금씩 느는거 같기도>?

728x90
반응형
Comments