2 Star 2 Fork 1

Justin Yuan/LeetCode-Swift

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ExamRoom.swift 1.12 KB
一键复制 编辑 原始数据 按行查看 历史
/**
* Question Link: https://leetcode.com/problems/exam-room/
* Primary idea: Calculate and compare middle point between two taken seats.
*
* Time Complexity: O(n) for seat(), O(1) for leave(at:), Space Complexity: O(n)
*
*/
class ExamRoom {
var seats: [Int]
init(_ n: Int) {
seats = Array(repeating: 0, count: n)
}
func seat() -> Int {
var maxDistance = 0, maxIndex = 0, lastOne = -1
for (i, seat) in seats.enumerated() {
if seat == 1 {
if lastOne == -1 {
if maxDistance < i {
maxDistance = i
maxIndex = 0
}
} else {
if maxDistance < (i - lastOne) / 2 {
maxDistance = (i - lastOne) / 2
maxIndex = lastOne + (i - lastOne) / 2
}
}
}
lastOne = i
}
if lastOne != -1 {
if maxDistance < (seats.count - 1 - lastOne) / 2 {
maxIndex = seats.count - 1
}
}
seats[maxIndex] = 1
return maxIndex
}
func leave(_ seat: Int) {
seats[seat] = 0
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/BiggerMax/LeetCode-Swift.git
git@gitee.com:BiggerMax/LeetCode-Swift.git
BiggerMax
LeetCode-Swift
LeetCode-Swift
master

搜索帮助