leetcode-第11场双周赛-5089-安排会议日程

题目描述:

 

自己的提交:

class Solution:
    def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
        res = []
        i,j = 0,0
        for start,end in slots1:
            if end - start < duration:
                i += 1
        if i == len(slots1):
            return []
        for start,end in slots2:
            if end - start < duration:
                j += 1
        if j == len(slots2):
            return []
        slots1.sort(key = lambda s:s[0])
        slots2.sort(key = lambda s:s[0])
        i,j = 0,0
        while i<len(slots1) and j<len(slots2):
            while slots1[i][0] >= slots2[j][1]:
                j += 1
            # while slots1[j][0] >= slots2[i][1]:
            #     i += 1
            time = min(slots1[i][1],slots2[j][1]) - max(slots1[i][0],slots2[j][0])
            if time < duration:
                if slots1[i][1] < slots2[j][1]: 
                    i += 1
                else:j += 1
            else:
                return [max(slots1[i][0],slots2[j][0]),max(slots1[i][0],slots2[j][0])+duration]
        return []

优化:

class Solution:
    def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
        slots1.sort()
        slots2.sort()
        m, n, i, j = len(slots1), len(slots2), 0, 0
        while i < m and j < n:
            (s1, e1), (s2, e2) = slots1[i], slots2[j]
            if e1 <= s2:
                i += 1
            elif e2 <= s2:
                j += 1
            else:
                s, e = max(s1, s2), min(e1, e2)
                if e - s >= duration:
                    return [s, s + duration]
                if e1 <= e2:
                    i += 1
                else:
                    j += 1
        return []

另:

class Solution(object):
    def minAvailableDuration(self, slots1, slots2, duration):
        events = []
        OPEN, CLOSE = 0, 1
        for a, b in slots1:
            events.append((a, OPEN))
            events.append((b, CLOSE))
        for a, b in slots2:
            events.append((a, OPEN))
            events.append((b, CLOSE))
        
        events.sort()
        prev = events[0][0]
        active = 0
        for x, cmd in events:
            if active == 2 and x - prev >= duration:
                return [prev, prev + duration]
            
            if cmd == OPEN:
                active += 1
            else:
                active -= 1

猜你喜欢

转载自www.cnblogs.com/oldby/p/11712566.html