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 start<left and end >left:
                ok = False
            if start>=left and start<right:
                ok = False
        
        for left in self.dic:
            right = self.dic[left]
            if start<left and end >left and ok:
                if right<= end:
                    self.cdic[left]=right
                else:
                    self.cdic[left]=end
            if start>=left and start<right and ok:
                if right<=end:
                    self.cdic[start]=right
                else:
                    self.cdic[start]=end
        if ok:
            self.dic[start]=end
        return ok


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

总结:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值