class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
answer = []
i, j = 0, 0
if len(firstList) == 0 or len(secondList) == 0:
return []
while i < len(firstList) and j < len(secondList):
if firstList[i][1] < secondList[j][0]:
i += 1
elif secondList[j][1] < firstList[i][0]:
j += 1
else:
intersection_start = max(firstList[i][0], secondList[j][0])
intersection_end = min(firstList[i][1], secondList[j][1])
answer.append([intersection_start, intersection_end])
if firstList[i][1] < secondList[j][1]:
i += 1
else:
j += 1
return answer
더 간단한 접근
class Solution:
def intervalIntersection(self, A, B):
i, j, ans = 0, 0, []
while i < len(A) and j < len(B):
curr = [max(A[i][0], B[j][0]), min(A[i][1], B[j][1])]
if curr[0] <= curr[1]:
ans.append(curr)
if A[i][1] <= B[j][1]:
i += 1
else:
j += 1
return ans
'CS > 알고리즘' 카테고리의 다른 글
[Leetcode] 1456. Maximum Number of Vowels in a Substring of Given Length (0) | 2023.05.06 |
---|---|
[Leetcode] 649. Dota2 Senate (0) | 2023.05.05 |
[Leetcode] 844. Backspace String Compare (0) | 2023.05.05 |
[Leetcode] 82. Remove Duplicates from Sorted List II (0) | 2023.05.04 |
[Leetcode] 2215. Find the Difference of Two Arrays (0) | 2023.05.03 |