LeetCode之Exam Room(Kotlin)
2019-07-25 本文已影响0人
糕冷羊
问题:
方法:
通过TreeSet作为座位的存储容器,leave时清空对应座位,seat时遍历所有入座情况,向符合要求的位置插入。
具体实现:
class ExamRoom(N: Int) {
private val N = N
private val seats = TreeSet<Int>()
fun seat(): Int {
var seat = 0
if (seats.isNotEmpty()) {
var dist = seats.first()
var pre: Int? = null
for (s in seats) {
if (pre != null) {
val d = (s - pre) / 2
if (d > dist) {
seat = pre + d
dist = d
}
}
pre = s
}
if (N - 1 - seats.last() > dist) {
seat = N - 1
}
}
seats.add(seat)
return seat
}
fun leave(p: Int) {
seats.remove(p)
}
}
fun main(args: Array<String>) {
val examRoom = ExamRoom(10)
examRoom.seat()
examRoom.seat()
examRoom.seat()
examRoom.seat()
}
有问题随时沟通