프로그래머스 (Swift)/기초

[Day6-4] 수열과 구간 쿼리 3

은더기 2024. 2. 9. 19:37

문제

 

내 정답 코드

import Foundation

func solution(_ arr:[Int], _ queries:[[Int]]) -> [Int] {
    
    var arr = arr
    
    for i in 0..<queries.count {
        let temp = arr[queries[i][0]]
        arr[queries[i][0]] = arr[queries[i][1]]
        arr[queries[i][1]] = temp
    }
    
    return arr
}

 

#

1. 반복문을 돌면서 필요한 값을 temp에 저장한다.

2. temp를 활용하여 원하는 위치에 값을 바꿔치기 한다.

 

@ swapAt라는 기술을 배워서 더 간단한 코드로 짜보았다.

import Foundation

func solution(_ arr:[Int], _ queries:[[Int]]) -> [Int] {
    
    var result = arr
    
    for i in 0..<queries.count {
        result.swapAt(queries[i][0], queries[i][1])
    }
    
    return result
}

배운 기술

 

1. swapAt

https://developer.apple.com/documentation/swift/array/swapat(_:_:)

 

swapAt(_:_:) | Apple Developer Documentation

Exchanges the values at the specified indices of the collection.

developer.apple.com