(사진: 프로그래머스 마스코트 머쓱이)
- 모든 원소 간의 합을 구해야 하기 때문에 이중 for문을 이용해야 한다. numbers의 모든 수가 100 이하기 때문에 성능에 문제 없다!
- 합이 중복될 수 있으므로 set을 사용해주었다.
- 배열에 오름차순으로 담아 반환해야 해서 sorted를 사용해주었다. set을 sorted한 후 array로 변환해주는 코드들도 봤는데, set이나 dictionary나 sorted를 사용하면 모두 배열로 변환되어 반환된다.
- for in을 사용할 때, ...numbers.count - 1 처럼 구체적인 인덱스를 지정해주었었다. ..<numbers.count 로 풀게 되면 인덱스 범위를 넘어서는 경우를 방지할 수 있고, 비교적 깔끔하다.
func solution(_ numbers:[Int]) -> [Int] {
var answer = Set<Int>()
for index in 0..<numbers.count {
for insideIndex in index + 1..<numbers.count{
answer.insert(numbers[index] + numbers[insideIndex])
}
}
return answer.sorted()
}
출처: https://programmers.co.kr/learn/courses/30/lessons/68644?language=swift
댓글