티스토리 뷰
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/76501
문제 사진
내 풀이
import Foundation
func solution(_ absolutes:[Int], _ signs:[Bool]) -> Int {
var result: [Int] = []
for (idx, el) in signs.enumerated() {
el == true ? result.append(absolutes[idx]) : result.append(-absolutes[idx])
}
return result.reduce(0, { $0 + $1 })
}
solution([4, 7, 12], [true, false, true])
- signs에서 false가 있는 index만 absolutes의 index로 접근해 ' - ' 로 바꾸기
- 위 내용을 적용하고 총합 구하기 (reduce)
다른사람의 풀이
import Foundation
func solution(_ absolutes:[Int], _ signs:[Bool]) -> Int {
return (0..<absolutes.count).map { signs[$0] ? absolutes[$0] : -absolutes[$0] }.reduce(0, +)
}
훨씬 더 깔끔하다
(0..<absolutes.count).map
이걸 index로 사용했다는점이 인상 깊었다.
728x90
'알고리즘' 카테고리의 다른 글
[Swift 알고리즘] - 인덱스 바꾸기 (Programmers) (0) | 2022.10.25 |
---|---|
[Swift 알고리즘] - 양꼬치 (Programmers) (0) | 2022.10.21 |
[Swift 알고리즘] - 약수의 개수와 덧셈 (Programmers) (0) | 2022.10.18 |
[Swift 알고리즘] - 하샤드 수 (Programmers) (0) | 2022.10.17 |
[Swift 알고리즘] - Stack으로 Queue만들기 (0) | 2022.10.14 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- swift reduce
- Swift 내림차순
- RIBs tutorial
- Class
- Swift init
- removeLast()
- Swift inout
- Combine: Asynchronous Programming with Swift
- Swift ModernRIBs
- Swift RIBs
- Swift joined()
- ios
- Swift joined
- swift property
- Swift
- swift programmers
- CS 네트워크
- Swift Leetcode
- Swift 프로그래머스
- Swift Error Handling
- swift protocol
- 원티드 프리온보딩
- RTCCameraVideoCapturer
- Swift 프로퍼티
- Swift final
- 2023년 회고
- swift (programmers)
- iOS error
- swift 고차함수
- Swift 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함