알고리즘/Programmers

[Swift_Programmes] K번째수

YEN_ 2024. 1. 4. 10:03

 

 

프로그래머스 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


💡 내가 제출한 풀이

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    
    var resultArr: [Int] = []
    var index0: Int = 0
    var index1: Int = 0
    var index2: Int = 0
    
    for i in 0 ..< commands.count {
        index0 = commands[i][0]
        index1 = commands[i][1]
        index2 = commands[i][2]
        
        resultArr.append(array[index0 - 1 ..< index1].sorted(by: <)[index2 - 1]) 
    }
    
    return resultArr
}


💡 풀이 과정

 

commands 내부 요소의 3개 숫자가 각각 i, j, k 이고 기준이 되는 배열은 array: [Int]이다.

  1. array를 i번째 숫자부터 j번째 숫자까지 자른다
  2. 오름차순 정렬한다
  3. 2번 배열의 k번째 숫자를 구한다
  4. commands의 모든 3번을 구하고 그 배열을 반환한다

대충 이런 문제인 것 같다. 어제 풀었던 문제도 마침 "정렬"을 하는 문제를 풀어서 sorted를 사용하면 되겠구나, 라고 바로 생각했다.

이 문제에서 주의할 점은 "i번째"  인 것이지 "인덱스가 i번째" 가 아니라는 걸 명심해야 할 것 같다.

 

 

array[index0 - 1 ..< index1]

 

우선 범위 연산자를 사용해서 i, j번째에 해당하는 범위의 배열을 잘라준다

 

array[index0 - 1 ..< index1].sorted(by: <)

 

sorted(by: <)로 오름차순 정렬을 해 주었다.

참고로 sorted(by: <)는 내림차순 정렬

 

array[index0 - 1 ..< index1].sorted(by: <)[index2 - 1]

 

마지막으로 k번째에 해당하는 요소를 골라서 resultArr에 append해서 반환할 배열을 만들었다.

 

 

 

 

 

💡 다른 버전의 풀이

사실 비슷한데 형태만 조..금.. 바꾼거다

속도가 빠른게 좋은건지 보기 편한게 좋은건지 모르겠당

 

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    
    var resultArr: [Int] = []
    
    for i in 0 ..< commands.count {
        let index0 = commands[i][0] - 1
        let index1 = commands[i][1]
        let index2 = commands[i][2] - 1
        
        resultArr.append(array[index0 ..< index1].sorted(by: <)[index2]) 
    }
    
    return resultArr
}

 

 

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    
    var resultArr: [Int] = []
    
    for i in 0 ..< commands.count {
        resultArr.append(array[commands[i][0] - 1 ..< commands[i][1]].sorted(by: <)[commands[i][2] - 1]) 
    }
    
    return resultArr
}


❗ 다른 사람의 풀이

import Foundation

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

 

내가 푼 방식에서 1번만 더 나아가면 이런 형태로 풀 수 있는 것 같다.

고차함수는 막상 쓰려면 생각이 안 나기 때문에..ㅠㅠ 의식적으로 사용하려고 노력해야 하는 것 같다.