[Algorithm🧬] K번째 수

또상·2021년 12월 2일
0

Algorithm

목록 보기
8/133
post-thumbnail

문제 / 풀이.py, [풀이.swift](

python

def solution(array, commands):
    answer = []
    
    for i in range(len(commands)):
        arr = array
        arr = arr[commands[i][0]-1: commands[i][1]]
        arr.sort()
            
        answer.append(arr[commands[i][2]-1])
        
    return answer

정렬을 이렇게 쉽게 해버리지 말고 정렬을 연습해보라고 낸 문제같은데.. 정렬을 직접 구현하기에는 알고리즘은 대강 기억나는데 정확한 멈춤 조건 같은 것이 기억이 안났다. 자료구조랑 정렬 공부해야하는데....


211123 swift

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {

    var answer: [Int] = []

    for i in commands.indices {
        answer.append(array[(commands[i][0] - 1)..<commands[i][1]].sorted()[commands[i][2]-1])
    }
    
    return answer
}

아니 처음에.. sort() 로 풀었는데 정렬은 되는데 계속 index 0 인거 넣어도 index error 나서 대체 뭘까........ 이랬는데... sort() 는 원본을 건드린다고 한다... 그래서 안됐구나....

profile
0년차 iOS 개발자입니다.

0개의 댓글