Archive/Questions
[programmers/Swift] 두 개 뽑아서 더하기
Marco
2022. 4. 28. 19:55
728x90
programmers.co.kr - 코딩테스트연습 - Lv.1 - 연습문제 - 두 개 뽑아서 더하기
Constraints :
- numbers의 길이는 2 이상 100 이하입니다.
- numbers의 모든 수는 0 이상 100 이하입니다.
//
// Created by Yongwoo Marco on 2022/04/25.
// Copyright © 2022 Yongwoo Marco Kim. All rights reserved.
//
func solution(_ numbers:[Int]) -> [Int] {
var result: Set<Int> = []
numbers.enumerated().forEach { baseIndex, base in
numbers.enumerated().forEach { otherIndex, other in
if baseIndex != otherIndex {
result.update(with: base + other)
}
}
}
return result.sorted(by: <)
}
print(solution([2,1,3,4,1])) // [2,3,4,5,6,7]
print(solution([5,0,2,7])) // [2,5,7,9,12]
How I tried this :
좀 더 깔끔한 방법이 없을까 고민했지만 자기 자신과 더하는 경우는 안되기 때문에
index를 확인해서 다른 수들을 더하는 방법으로 처리하고
중복된 수를 제거하기 위해 Set을 사용했다.
문제에 관한 모든 저작권 : https://programmers.co.kr/
728x90