leetcode 729和731的坑

两道题都是日程表,729有重叠则返回false,731有两次重叠返回false。

用python字典来保存时间段看似可行实则不行,key的唯一性决定了若两段时段的start相同,则后一段会覆盖前一段,造成错误。

比如:

dic ={}
dic[23]=45
dic[23]=47
print(dic)
#结果会是{23:47}

729可通过,731不行。

729代码:

class MyCalendar:
    dic = {}

    def __init__(self):
        self.dic = {}

    def book(self, start, end):
        """
        :type start: int
        :type end: int
        :rtype: bool
        """
        ok =True
        for left in self.dic:
            right = self.dic[left]
            if start < left and end >left:
                ok = False
            if start < right and start>=left:
                ok = False
        if ok:
            self.dic[start]=end
        return ok
                


# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)

731代码:

class MyCalendarTwo:
    dic = {}
    cdic = {}

    def __init__(self):
        self.dic = {}
        self.cdic = {}

    def book(self, start, end):
        """
        :type start: int
        :type end: int
        :rtype: bool
        """
        ok = True   
        for left in self.cdic:
            right=self.cdic[left]
            if startleft:
                ok = False
            if start>=left and startleft and ok:
                if right<= end:
                    self.cdic[left]=right
                else:
                    self.cdic[left]=end
            if start>=left and start

总结:

类似求区间交叠的问题应用list来存储区间,字典看似讨巧,实则不行

你可能感兴趣的:(算法)