美文网首页
LeetCode之Exam Room(Kotlin)

LeetCode之Exam Room(Kotlin)

作者: 糕冷羊 | 来源:发表于2019-07-25 17:54 被阅读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()
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Exam Room(Kotlin)

          本文链接:https://www.haomeiwen.com/subject/nshkrctx.html