iOS/알고리즘

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

kihun5393 2021. 8. 12. 18:58

https://programmers.co.kr/learn/courses/30/lessons/42748

 

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

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

제출한 답안

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    var cutArray = [Int]()
    var returnArray = [Int]()
    
    for command in commands {
        cutArray = [Int]()
        
        for num in array[(command[0]-1)...(command[1]-1)] {
            cutArray.append(num)
        }
        
        cutArray.sort()
        returnArray.append(cutArray[(command[2]-1)])
    }
    
    return returnArray
}

'정렬을 내가 해야할까?' 잠시 생각해봤다가 찾아보니 swift에서 정렬을 지원하네요.

sort() 이거면 배열 안의 내용 자체를 정렬해줍니다. 이거 말고도 리버스 등등 여러 메소드를 지원합니다.

정렬 등 지원하는 메소드에 대한 공식문서입니다.

https://developer.apple.com/documentation/swift/array/1688499-sort

 

Apple Developer Documentation

 

developer.apple.com


다시 풀어본 답안

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    return commands.map({ array[($0[0]-1)...($0[1]-1)].sorted()[$0[2]-1] })
}

map을 사용해보았습니다.

array에 접근해서 실행하는 commands의 각 요소 부분이 똑같은 실행을 반복하기에 map으로 처리가 가능합니다.

for num in array[(command[0]-1)...(command[1]-1)] {
  cutArray.append(num)
}

returnArray.append(cutArray.sorted()[(command[2]-1)])

이 부분을 map으로 처리한 것이고 

sorted() 로 정렬된 배열을 얻어와 바로 처리하였습니다.