Roel Notebook

[Swift] 프로그래머스 K번째수

by Roel Downey
728x90
반응형

K번째수

 

 

문제 

- 문제 링크: 프로그래머스

 

 

풀이

func slideArray(array: [Int], inside: Int, outside: Int) -> [Int] {
    var result = [Int]()
    var min = 0
    var max = 0
    
    if inside <= outside {
        min = inside - 1
        max = outside - 1
    } else {
        min = outside - 1
        max = inside - 1
    }
    
    for min in min...max {
        result.append(array[min])
    }
    return result.sorted()
}

func selectPic(array: [Int], number: Int) -> Int {
    return array[number-1]
}

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    var result = [Int]()
    for index in 0..<commands.count {
        let com = commands[index]
        let resultArray = slideArray(array: array, inside: com[0], outside: com[1])
        result.append(selectPic(array: resultArray, number: com[2]))
    }
    
    return result
}

 

import Foundation

    private func subarray(from origin:[Int], begin: Int, end: Int) -> [Int] {
        var split = [Int]()
        for item in origin.index(0, offsetBy: begin-1)...origin.index(0, offsetBy: end-1) {
            split.append(origin[item])
        }
        return split
    }

    func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
        var result = [Int]()
        for indecies in commands {
            let sub = subarray(from: array, begin: indecies[0], end: indecies[1])
            let sorted = sub.sorted()
            result.append(sorted[sorted.index(0, offsetBy: indecies[2]-1)])
        }
        return result
    }
728x90
반응형

블로그의 정보

What doing?

Roel Downey

활동하기