ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฒด์œก๋ณต(Swift)

2022. 10. 2. 16:16ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฒด์œก๋ณต(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/42862

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 ๋‚˜์˜ ํ’€์ด

 

์—ฌ๋ถ„์ด ์žˆ๋Š” ๋ฐฐ์—ด์„ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ์žƒ์–ด๋ฒ„๋ฆฐ ๋ฐฐ์—ด์˜ ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ์—†์• ๊ณ , ์•ž์˜ ๋ฒˆํ˜ธ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด ์•ž์—๋ถ€ํ„ฐ, ๊ทธ ๋‹ค์Œ ๋’ค์— ๋ฒˆํ˜ธ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด ๋’ค์— ๋ฒˆํ˜ธ์—๊ฒŒ ์ค˜์„œ ํ•ด๊ฒฐํ–ˆ์ง€๋งŒ 20๊ฐœ์˜ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์—์„œ 1๊ฐœ์˜ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋ฅผ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ–ˆ๋‹ค.

 

๊ณ ๋ฏผ ํ›„ ์งˆ๋ฌธํ•˜๊ธฐ๋ฅผ ํ†ตํ•ด 5๋ฒˆ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์˜ ๋ฌธ์ œ๋ฅผ ํ™•์ธํ–ˆ๋Š”๋ฐ ์—ฌ๋ถ„์ด ์žˆ๋Š”๋ฐ ์žƒ์–ด๋ฒ„๋ฆฐ ๊ฒฝ์šฐ๋Š” ์—ฌ๋ถ„์ด ์žˆ๋Š” ๋ฐฐ์—ด์„ ํƒ์ƒ‰ํ•˜๊ธฐ ์ „์— ์ฒ˜๋ฆฌํ•ด์ค˜์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ด์—ˆ๋‹ค. 

์˜ˆ๋ฅผ ๋“ค์–ด [5, 7]์ด ์žƒ์–ด๋ฒ„๋ฆฐ ๋ฐฐ์—ด์ด๊ณ  [4, 5, 8]์ด ์—ฌ๋ถ„์˜ ๋ฐฐ์—ด์ผ ๋•Œ ์—ฌ๋ถ„์˜ ๋ฐฐ์—ด์„ ๋ฐ”๋กœ ํƒ์ƒ‰ํ•˜๋ฉด 4๋ฒˆ์ด 5๋ฒˆ์˜ ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ฃผ๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธฐ๋Š” ๊ฒƒ์ด๋‹ค. (์›๋ž˜๋Š” ์žƒ์–ด๋ฒ„๋ฆฐ ๋ฒˆํ˜ธ์™€ ์—ฌ๋ถ„์˜ ๋ฒˆํ˜ธ๊ฐ€ ๊ฐ™์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ ์ž๊ธฐ๋ฅผ ์ œ์™ธํ•ด์•ผ ํ•œ๋‹ค)

 

๋ฌธ์ œ๋ฅผ ์ž˜ ์ฝ์–ด๋ณด๊ณ  ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋Šฅ๋ ฅ์ด ๋ถ€์กฑํ–ˆ๋‹ค. 

์—ฌ๋ฒŒ ์ฒด์œก๋ณต์„ ๊ฐ€์ ธ์˜จ ํ•™์ƒ์ด ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ–ˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋•Œ ์ด ํ•™์ƒ์€ ์ฒด์œก๋ณต์„ ํ•˜๋‚˜๋งŒ ๋„๋‚œ๋‹นํ–ˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉฐ, ๋‚จ์€ ์ฒด์œก๋ณต์ด ํ•˜๋‚˜์ด๊ธฐ์— ๋‹ค๋ฅธ ํ•™์ƒ์—๊ฒŒ๋Š” ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ค„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

 

import Foundation

func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
    
    var lostArr = lost.sorted(by: <)
    var reserveArr = reserve.sorted(by: <)
    
    reserveArr = reserveArr.filter{ 
        if lostArr.contains($0) {
            if let index = lostArr.firstIndex(of: $0) {
                lostArr.remove(at: index)
            }
            return false
        } else {
            return true
        }
    }
    
    for num in reserveArr {
        if lostArr.contains(num-1) {
            if let index = lostArr.firstIndex(of: num-1) {
                lostArr.remove(at: index)
            }
        } else if lostArr.contains(num+1) {
            if let index = lostArr.firstIndex(of: num+1) {
                lostArr.remove(at: index)
            }
        }
        
    }
    
    return n-lostArr.count
}

 

 

 ํ”ผ๋“œ๋ฐฑ

 

1. ๋ฌธ์ œ๋Š” ๋ชจ๋“  ๋ฌธ์žฅ์ด ๋ฌธ์ œ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ˆจ๊ฒจ์ง„ ์˜๋ฏธ๋ฅผ ์ฐพ์œผ๋ ค๊ณ  ๋…ธ๋ ฅํ•ด์•ผํ•œ๋‹ค. 

2. ๋ฐฐ์—ด์˜ ๊ฐ’์„ ์ง€์šฐ๋Š” ๊ฒƒ์€ remove๋‚˜ filter๋กœ ์ง€์šธ ์ˆ˜ ์žˆ์œผ๋ฉฐ remove๋ฅผ ์ด์šฉํ•  ๋•Œ๋Š” firstIndex๋กœ ์ฐพ๊ณ  if let๋ฐ”์ธ๋”ฉ์„ ํ†ตํ•ด์„œ ์ง€์›Œ์•ผํ•œ๋‹ค.