import Foundation
/// ์นด๋๋ 1 ~ N๊น์ง ๋ฒํธ ๋ถ์ด์์
/// 1๋ฒ ์นด๋๊ฐ ์ ์ผ ์, N๋ฒ์นด๋๊ฐ ์ ์ผ ์๋
/// ์๋ ์ฌํญ์ ๋ฐ๋ณต
/// 1. ์ ์ผ ์์ ์นด๋๋ฅผ ๋ฐ๋ฅ์ ๋ฒ๋ฆผ
/// 2. ์ ์ผ ์์ ์นด๋๋ฅผ ์ ์ผ ์๋ ์นด๋ ๋ฐ์ผ๋ก ์ฎ๊น
/// ๋ง์ง๋ง์ผ๋ก ๋จ๊ฒ๋๋ ์นด๋๋ ๋ญ๋?
let N = Int(readLine()!)!
var cards = Array(1...N)
var queue = Queue<Int>()
for i in 1...N {
queue.enqueue(i)
}
while queue.count >= 2 {
queue.dequeue()
if let dequeue = queue.dequeue() {
queue.enqueue(dequeue)
}
}
print(queue.dequeue()!)
struct Queue<T> {
private var queue: [T?] = []
private var head: Int = 0
public var count: Int {
return queue.count
}
public var isEmpty: Bool {
return queue.isEmpty
}
public mutating func enqueue(_ element: T) {
queue.append(element)
}
@discardableResult
public mutating func dequeue() -> T? {
guard head <= queue.count, let element = queue[head] else { return nil }
queue[head] = nil
head += 1
if head > (count / 4) {
queue.removeFirst(head)
head = 0
}
return element
}
}
์๊ฐ๋ณต์ก๋๊ฐ O(1)์ธ queue๋ฅผ ์ฌ์ฉํ์ฌ ํด๊ฒฐํ๋ค.
๋ฐ์ํ
'๐ ์ฝํ > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๋ฐฑ์ค2609 (0) | 2023.03.27 |
---|---|
[Swift] ๋ฐฑ์ค2231 (0) | 2023.03.24 |
[Swift] ๋ฐฑ์ค1966 (0) | 2023.03.24 |
[Swift] ๋ฐฑ์ค1436 (0) | 2023.03.23 |
[Swift] ๋ฐฑ์ค1181 (0) | 2023.03.23 |