LeetCode之Exam Room(Kotlin)

问题:


LeetCode之Exam Room(Kotlin)_第1张图片

方法:
通过TreeSet作为座位的存储容器,leave时清空对应座位,seat时遍历所有入座情况,向符合要求的位置插入。

具体实现:

class ExamRoom(N: Int) {
    private val N = N

    private val seats = TreeSet()

    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) {
    val examRoom = ExamRoom(10)
    examRoom.seat()
    examRoom.seat()
    examRoom.seat()
    examRoom.seat()
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Exam Room(Kotlin))