美文网首页
骨骼清奇Sort Property

骨骼清奇Sort Property

作者: SharlotteZZZ | 来源:发表于2018-10-16 03:31 被阅读0次

Catalog:
LC 855 Exam Room

Notes:
When you sort a dictionary, you are sorting based on keys by default and sorted(d) will return the sorted key list for you. If you want to get key list based on sorted values, try the following:

k1 = sorted(d, key=lambda x: d[x])
k2 = sorted(d, key=lambda x: d[x], reverse = True)

LC 855 Exam Room [freq:6]
ExamRoom.seat() returning an int representing what seat the student sat in, which maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. (Also, if no one is in the room, then the student sits at seat number 0.)
ExamRoom.leave(int p) representing that the student in seat number p now leaves the room. It is guaranteed that any calls to ExamRoom.leave(p) have a student sitting in seat p.

Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
Output: [null,0,9,4,2,null,5]
ExamRoom(10) -> null
seat() -> 0, no one is in the room, then the student sits at seat number 0.
seat() -> 9, the student sits at the last seat number 9.
seat() -> 4, the student sits at the last seat number 4.
seat() -> 2, the student sits at the last seat number 2.
leave(4) -> null
seat() -> 5, the student sits at the last seat number 5.

class ExamRoom(object):
    def __init__(self, N):
        self.N = N
        self.students = []

    def seat(self):
        if not self.students:
            student = 0
        else:
            # We start by considering the left-most seat.
            dist, student = self.students[0], 0
            for i, s in enumerate(self.students):
                if i:
                    prev = self.students[i-1]
                    # d - distance to the closest student
                    # at position prev + d.
                    d = (s - prev) // 2
                    if d > dist:
                        dist, student = d, prev + d

            # Considering the right-most seat!!!
            d = self.N - 1 - self.students[-1]
            if d > dist:
                student = self.N - 1

        # Add the student to our sorted list of positions.
        bisect.insort(self.students, student)
        return student

    def leave(self, p):
        self.students.remove(p)

相关文章

网友评论

      本文标题:骨骼清奇Sort Property

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