Focus On Develop ๐ŸคŸ๐ŸคŸ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ ๋ณธ๋ฌธ

iOS [Swift]/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2020. 12. 15. 16:51

<๋ฌธ์ œ>

์ด ๋ฌธ์ œ๋Š” ์ •์ˆ˜ํ˜• ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง€๊ณ , ๊ทธ ์•ˆ์—์„œ ์ž„์˜์˜ ๋‘ ์ˆซ์ž๋ฅผ ๊ณจ๋ผ ๋‘ ์ˆ˜๋ฅผ ํ•ฉํ•œ ๊ฐ’์˜ ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋‹ค.

 


<์ „๋žต์งœ๊ธฐ>

์ œํ•œ์‚ฌํ•ญ์— ์ฃผ์–ด์ง€๋Š” ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ๋ณด๋ฉด Worst Case์˜ ํƒ์ƒ‰ ํšŸ์ˆ˜๋Š” 10000ํšŒ (100x100) ์ธ๋ฐ, ์‚ฌ์‹ค์ƒ ์ด์ •๋„๋Š” ์ œํ•œ์‹œ๊ฐ„์— ์˜ํ–ฅ์„ ๋ฏธ์น˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ํŒ๋‹จํ–ˆ๋‹ค. (1์–ตํšŒ ์—ฐ์‚ฐ/ํƒ์ƒ‰ ๊ธฐ์ค€ 1์ดˆ๋กœ ํŒ๋‹จ)

๊ทธ๋ƒฅ Brute force ๋ฐฉ์‹์œผ๋กœ ๋ฐฐ์—ด์„ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ๋‘ ์ˆ˜์˜ ํ•ฉ์„ ๋ชจ์€ ๋’ค์— ๋งˆ์ง€๋ง‰์— ์ค‘๋ณต์ œ๊ฑฐ, ์ •๋ ฌ๋งŒ ํ•ด์ฃผ๋ฉด ๋˜๊ฒ ๊ตฌ๋‚˜.

์ •๋ ฌ์€ Array์—์„œ ์ œ๊ณตํ•˜๋Š” .sorted() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ , ์ค‘๋ณต์ œ๊ฑฐ๋Š” Set์„ ์ด์šฉํ•˜๋ฉด ๋˜๊ฒ ๋Š”๊ฑธ..!?

 

<์ฝ”๋“œ>

import Foundation

var result: [Int] = []

func solution(_ numbers:[Int]) -> [Int] {
    for i in 0 ..< numbers.count {
        for j in 1 ..< numbers.count {
            if i == j {
                continue
            } 
            result.append(numbers[i] + numbers[j])
        }
    }
    
    let resultSet = Set(result)
    let resultArray = Array(resultSet)
    result = resultArray.sorted()

    return result
}

 

<Lessons Learned>

์ •๋‹ต์œผ๋กœ ํ†ต๊ณผํ•˜๊ธด ํ–ˆ์ง€๋งŒ ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ์•„์ฐจ ์‹ถ์—ˆ๋‹ค ใ…Žใ…Ž

๋‚˜๋Š” "๋ฐฐ์—ด์—์„œ ์ค‘๋ณต์ œ๊ฑฐ๋ฅผ ์œ„ํ•ด์„œ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ์ž๋ฃŒ๊ตฌ์กฐ ์ค‘ ํ•˜๋‚˜์ธ Set์„ ์ด์šฉํ•˜๋ฉด ์‰ฝ๊ฒ ๊ตฌ๋‚˜." ํ•˜๊ณ  ์‰ฝ๊ฒŒ ์ƒ๊ฐํ•œ ๊ฒƒ ๊ฐ™๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋Š” ๋ฐฉ๋ฒ• ๋Œ€์‹ , result ๋ฐฐ์—ด์— ๋‘ ์ˆ˜์˜ ํ•ฉ์˜ ๊ฒฝ์šฐ๋ฅผ ๋„ฃ์–ด์ฃผ๋Š” ๊ณผ์ •์—์„œ .contains() ๋ฉ”์†Œ๋“œ๋กœ ๋ฐ”๋กœ๋ฐ”๋กœ ์ค‘๋ณต์ฒดํฌ๋ฅผ ํ•ด์คฌ์œผ๋ฉด ๋” ์ข‹์•˜์„ ๋“ฏ ํ•˜๋‹ค..

if !result.contains(num) {
	result.append(num)
}

๋ถˆํ•„์š”ํ•œ Array -> Set -> Array ๋กœ์˜ ๋ณ€๊ฒฝ์— ๋Œ€ํ•œ ๋ฉ”๋ชจ๋ฆฌ/์‹œ๊ฐ„์„ ์ด๋“์„ ๋ณผ ์ˆ˜ ์žˆ์—ˆ์„ํ…๋ฐ. ๐Ÿ˜‚

 

 

์•Œ๊ณ ๋ฆฌ์ฆ˜์—์„œ ์‚ฌ์šฉํ•œ Set ๋‚ด์šฉ์ด ๊ถ๊ธˆํ•˜๋‹ค๋ฉด ? ๐Ÿ‘‰ 2020/12/15 - [iOS/๊ธฐ์ดˆ๋ฅผ ํƒ„ํƒ„ํžˆ!] - [Swift] Set

 

 

# ์ถœ์ฒ˜ : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋‘ ๊ฐœ ๋ฝ‘์•„์„œ ๋”ํ•˜๊ธฐ

Comments