(Swift) Programmers K번째수

SteadySlower·2022년 9월 15일
0

Coding Test

목록 보기
158/298

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

문제 풀이 아이디어

주어진 연산을 그대로 코드로 옮기기만 하면 되는 문제입니다.

Array를 slice하는 방법을 알고 있어야 합니다. subscript와 range를 조합해서 사용하면 됩니다.

코드

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    func operation(_ command: [Int]) -> Int {
        array[(command[0] - 1)..<command[1]].sorted()[command[2] - 1]
        //👉 i ~ j까지 자르고 / 정렬한 다음 / k번째 수를 리턴한다.
    }
    
    var result = [Int]()
    
    for command in commands {
        result.append(operation(command))
    }
    
    return result
}
profile
백과사전 보다 항해일지(혹은 표류일지)를 지향합니다.

0개의 댓글