본문 바로가기
#알고리즘 [Algorithm]/Problem

[프로그래머스 - 정렬] K번째수

by cy_mos 2019. 4. 5.
반응형

[프로그래머스 - 정렬] K번째수


📄 [정렬] K번째수 C++ Source Code

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

const int findTarget(const vector<int> & arr, const int left, const int right, const int target) {

	vector<int> bucket = vector<int>(arr.begin() + left, arr.begin() + right);
	std::sort(bucket.begin(), bucket.end());

	return bucket[target];
}

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

	for (const auto command : commands) {
		const auto number = findTarget(array, command[0] - 1, command[1], command[2] - 1);
		answer.push_back(number);
	}

	return answer;
}

📄 [정렬] K번째수 Swift Source Code

import Foundation

func findTarget(array: [Int], left: Int, right: Int, index: Int) -> Int {
    
    var copyArray = Array(array[left...right])
    copyArray.sort()
    
    return copyArray[index - 1]
}

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    
    var answer = Array<Int>()
    
    for value in commands {
        let command: (left: Int, right: Int, index: Int) = (value[0] - 1, value[1] - 1, value[2])
        let target = findTarget(array: array, left: command.left, right: command.right, index: command.index)
        
        answer.append(target)
    }
    
    return answer
}

🚀 REFERENCE

반응형

댓글