Algorithm/프로그래머스

[프로그래머스/level1/c++]K번째수

호_두씨 2020. 12. 31. 00:54

문제 : 

배열 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]

 

코드 : 

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

using namespace std;

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

 

다시 한번 짚고 넘어가기 :

-vector 복사하는 방법

  1)new_vector.assign(old_vector.begin(),old_vector.end());

  2)new_vector=old_vector;

  ->2)를 사용한 코드

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

using namespace std;

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

 

-sort함수 : c++의 algorithm헤더에 포함, 기본적으로 오름차순 정렬

 sort(a,b)이라면 첫번째 인자는 배열의 시작지점(iterator(포인터)에서 정렬 시작 지점), 두번째 인자는 배열의 끝나는 지점+1(정렬을 마칠 지점)이다.

 ex) int a[3]={1,2,3};

      sort(a,a+3) //시작지점,시작지점+크기

 

 

도움이 된 글:

qastack.kr/programming/644673/fast-way-to-copy-one-vector-into-another

 

한 벡터를 다른 벡터로 복사하는 빠른 방법

 

qastack.kr