๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

์ •์ˆ˜ ๋ฐฐ์—ด numbers๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์—์„œ ์„œ๋กœ ๋‹ค๋ฅธ ์ธ๋ฑ์Šค์— ์žˆ๋Š” ๋‘ ๊ฐœ์˜ ์ˆ˜๋ฅผ ๋ฝ‘์•„ ๋”ํ•ด์„œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • numbers์˜ ๊ธธ์ด๋Š” 2 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
    • numbers์˜ ๋ชจ๋“  ์ˆ˜๋Š” 0 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
 numbers result
[2,1,3,4,1] [2,3,4,5,6,7]
[5,0,2,7] [2,5,7,9,12]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import Foundation

func solution(_ numbers:[Int]) -> [Int] {
    var result = [Int]()
    for i in 0..<numbers.count-1 {
        for j in i+1..<numbers.count {
            if !result.contains(numbers[i] + numbers[j]) {
                result.append(numbers[i] + numbers[j])
            }
        }
    }
    return result.sorted()
}
  • 2์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‘ ์ˆ˜๋ฅผ ๋”ํ•˜๋Š” ๋ฐ˜๋ณต๋ฌธ์„ ์ž‘์„ฑํ–ˆ๊ณ , result ๋ฐฐ์—ด์— ๊ฐ™์€ ์ˆ˜๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ์—†๋‹ค๋ฉด append ํ•ด์ฃผ์—ˆ์Œ.
  • ๋ฆฌํ„ด๋ฌธ์—์„œ ์ •๋ ฌํ•˜์—ฌ ๋ฐ˜ํ™˜.

 

์ธ์ƒ์ ์ธ ํ’€์ด
import Foundation

func solution(_ numbers:[Int]) -> [Int] {

    var arr:[Int] = []

    for i in 0..<numbers.count {
        for j in i+1..<numbers.count {
            arr.append(numbers[i]+numbers[j])
        }
    }

    return Set(arr).sorted()
}
  • ์ค‘๋ณต ๊ฒ€์‚ฌ๋ฅผ ํ•˜์ง€ ์•Š๊ณ  ๋ฐฐ์—ด์— ๋”ํ•œ ์ˆ˜๋“ค์„ ์ €์žฅ, ๋ฆฌํ„ด๋ฌธ์—์„œ set๋ฅผ ์ด์šฉํ•˜์—ฌ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ  sorted ํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • Set ์ด์šฉํ•˜๋‹ˆ ๊ตณ์ด ์ค‘๋ณต ์ œ๊ฑฐ๋ฅผ ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค,,! ์•ž์œผ๋กœ Set๋ฅผ ์ž˜ ํ™œ์šฉํ•ด๋ด์•ผ๊ฒ ๋‹ค.

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution2(_ numbers:[Int]) -> [Int] {
    var res = Set<Int>()
    for i in 0..<numbers.count-1 {
        for j in i+1..<numbers.count { res.insert(numbers[i]+numbers[j]) }
    }
    return res.sorted()
}
  • Set ์‚ฌ์šฉํ•˜์—ฌ ์ž๋™์œผ๋กœ ์ค‘๋ณต ๊ฒ€์‚ฌํ•ด์ฃผ์—ˆ๊ณ , ๋•๋ถ„์— ์ฒซ ํ’€์ด๋ณด๋‹ค ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•ด์กŒ๋‹ค.

 


 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/68644

๋Œ“๊ธ€