ved_Rony

문제 설명

배열 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 함수를 작성해주세요.

1. 주어진 배열을 주어진 범위로 자르고, 

2. 정렬하여. 타겟 인덱스의 값을 가져온다.

#include <string>
#include <vector>

using namespace std;
//정렬을 직접 구현 해봤다.
vector<int> Sorting(vector<int> target) {
  int temp = 0;
 //맨앞에서부터 맨끝의 -1번째 까지 꺼낸다
  for (int i = 0; i < target.size() - 1; i++) {
  //꺼낸수의 +1번째 부터 크기를 비교하여 정렬한다
    for (int j = i + 1; j < target.size(); j++) {
    //정렬 조건은 맨처음 꺼낸 i번째의 수가 j번째보다 클 때, j번째 수를 i번째로 옮기고
    //다음 차례로 간다. 이경우 가장 가장 작은수가 앞으로 오게 된다.
    //오름차순
      if (target[i] > target[j]) {
        temp = target[i];
        target[i] = target[j];
        target[j] = temp;
      }
    }
  }
  return target;
}
//시작 인덱스와 마지막 인덱스 까지만 타겟 배열을 복사해서 
int CopyArray(vector<int> targetArray, int startIndex, int endIndex,
              int targetIndex) {
  //새롭게 정렬할 배열 선언
  vector<int> target;
  //잘라낼 배열 부분 가져오기
  for (int i = startIndex - 1; i <= endIndex - 1; i++) {
    target.push_back(targetArray[i]);
  }
//정렬
  target = Sorting(target);
//타겟 index의 숫자 return
  return target[targetIndex - 1];
}

vector<int> solution(vector<int> array, vector<vector<int>> commands) {

  vector<int> answer;
  for (int i = 0; i < commands.size(); i++) {
    answer.push_back(
        CopyArray(array, commands[i][0], commands[i][1], commands[i][2]));
  }

  return answer;
}

c++ 문법에 익숙하지가 않아서, 정렬 메소드를 직접 구현했다. 쉬운 문제임에도 오래 걸려서 풀게 됐다.

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

모범 답안이다. sort함수에서  sort시작 범위와 마지막 범위를 선정 할수가 있다.

 answer.push_back(temp[commands[i][0] + commands[i][2]-2]); 부분에서 그냥 자른 상태에서 targetindex이기 때문에 

자르는 범위의 시작 index + targetindex해줌으로서 원하는 답을 얻을수가 있다. 아름답다.

profile

ved_Rony

@Rony_chan

검색 태그