정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.
입출력 예
numbers | result |
---|---|
[2,1,3,4,1] | [2,3,4,5,6,7] |
[5,0,2,7] | [2,5,7,9,12] |
주어진 numbers의 각 element들을 더해서 (본인끼리 더하기 제외) 중복되는 결과값 없이 오름차순으로 정렬된 배열을 return하면 된다.
bubble sort로 모든 element를 돌면서, 중복되는 결과값이 없애기 위해 Set을 활용한다.
import Foundation
func solution(_ numbers:[Int]) -> [Int] {
var result: Set<Int> = []
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
result.insert(numbers[i]+numbers[j])
}
}
return Array(result).sorted()
}