ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ–ฅ ๋ฌธ์ œ

์ „์ฒด ํ•™์ƒ์˜ ์ˆ˜ n, ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ๋“ค์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด lost, ์—ฌ๋ฒŒ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ ธ์˜จ ํ•™์ƒ๋“ค์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด reserve๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์ฒด์œก์ˆ˜์—…์„ ๋“ค์„ ์ˆ˜ ์žˆ๋Š” ํ•™์ƒ์˜ ์ตœ๋Œ“๊ฐ’์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

๐Ÿค” ํ’€์ด ๋ฐฉ๋ฒ•

  1. var possible = Array(repeating: 1, count: n)
    • n๋ช…์˜ ํ•™์ƒ์ด ๋ชจ๋‘ ์ฒด์œก๋ณต์„ ํ•˜๋‚˜์”ฉ ๊ฐ€์ ธ์™”๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ  ๋ฐฐ์—ด์„ 1๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  2. ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ์˜ ์ฒด์œก๋ณต์„ -1ํ•ด ์ฃผ๊ณ  ์—ฌ๋ฒŒ ์ฒด์œก๋ณต์ด ์žˆ๋Š” ํ•™์ƒ๋“ค์˜ ์ฒด์œก๋ณต์„ +1 ํ•ด์ค€๋‹ค.
    for i in lost { possible[i - 1] -= 1 }
    for i in reserve { possible[i - 1] += 1 }
  3. if i != 0 && possible[i - 1] == 2 && possible[i] == 0 {}
    • 2๋ฒˆ ํ•™์ƒ์ด ์ฒด์œก๋ณต์ด ์—†๊ณ , 1๋ฒˆ ํ•™์ƒ์ด 2๊ฐœ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง€๊ณ  ์žˆ์„ ๊ฒฝ์šฐ 2๋ฒˆ ํ•™์ƒ์ด 1๋ฒˆ ํ•™์ƒ์—๊ฒŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ฆฐ๋‹ค.
  4. else if i != n - 1 && possible[i] == 0 && possible[i + 1] == 2 {}
    • 2๋ฒˆ ํ•™์ƒ์ด ์ฒด์œก๋ณต์ด ์—†๊ณ , 1๋ฒˆ ํ•™์ƒ์ด 2๊ฐœ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง€๊ณ  ์žˆ์ง€ ์•Š์„ ๊ฒฝ์šฐ
    • 3๋ฒˆ ํ•™์ƒ์ด 2๊ฐœ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง€๊ณ  ์žˆ์„ ๊ฒฝ์šฐ 2๋ฒˆ ํ•™์ƒ์ด 3๋ฒˆ ํ•™์ƒ์—๊ฒŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ฆฐ๋‹ค.

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป Swift Code

import Foundation

func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
    var possible = Array(repeating: 1, count: n)
    var answer = 0

    for i in lost { possible[i - 1] -= 1 }
    for i in reserve { possible[i - 1] += 1 }

    for i in 0..<n {
        if i != 0 && possible[i - 1] == 2 && possible[i] == 0 {
            possible[i - 1] = 1
            possible[i] = 1
        } else if i != n - 1 && possible[i] == 0 && possible[i + 1] == 2 {
            possible[i] = 1
            possible[i + 1] = 1
        }
    }

    for i in 0..<n {
        if possible[i] != 0 {
            answer += 1
        }
    }

    return answer
}

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ฒด์œก๋ณต

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

programmers.co.kr

 

๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
๊ธ€ ๋ณด๊ด€ํ•จ