Where who wants to meet someone

수열과 구간 쿼리 3 본문

프로그래머스 알고리즘 문제 기록/코딩 기초 트레이닝

수열과 구간 쿼리 3

Lust3r 2024. 1. 11. 13:07
728x90

문제

https://school.programmers.co.kr/learn/courses/30/lessons/181924

 

프로그래머스

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

programmers.co.kr

 

내 답안 / 다른 사람들의 답안

import Foundation

func solution(_ arr:[Int], _ queries:[[Int]]) -> [Int] {
    var newArr = arr

    for query in queries {
        newArr.swapAt(query[0], query[1])
    }

    return newArr
}

- 내장 메서드 swapAt을 사용하여 각 query의 0, 1 인덱스의 값을 바꿔주었다.

 

func solution(_ arr: [Int], _ queries: [[Int]]) -> [Int] {
    return queries.reduce(into: arr) { result, q in
        result.swapAt(q[0], q[1])
    }
}

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

 

reduce(into:_:) | Apple Developer Documentation

Returns the result of combining the elements of the sequence using the given closure.

developer.apple.com

- 설명에 따르면 이 메서드는 결과가 배열이나 딕셔너리처럼 copy-on-write 유형인 경우 효율성을 위해 reduce(_:_:)보다 선호된다고 한다. updateAccumulatingResult에 result가 inout으로 들어오기 때문에 변형할 arr를 result로 사용하고, 클로저에서 어떤 작업을 수행할 지 구성

- result값과 queries의 query(코드에서는 q)를 사용하여 result에서 query의 인덱스 값으로 swapAt 메서드를 수행

- 수행한 결과를 arr에 반영하여 return 하는 방식

 

reduce(_:_:) 메서드만 사용했었는데 새로운 메서드를 해당 답변을 통해 알 수 있었다.

 

점수: +1

'프로그래머스 알고리즘 문제 기록 > 코딩 기초 트레이닝' 카테고리의 다른 글

콜라츠 수열 만들기  (0) 2024.01.16
카운트 업  (0) 2024.01.16
배열 만들기 2  (0) 2024.01.16
수열과 구간 쿼리 4  (0) 2024.01.15
수열과 구간 쿼리 2  (0) 2024.01.12