Leetcode区间列表的交集
我的解法:
需要考虑的情况很多,需要同时考虑左右和重叠的情况,当一个列表遍历到头的时候就要
强制遍历第二个列表,不然会一直卡死,同时必须同时遍历完两个列表才能结束
class Solution:def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:if firstList==[] or secondList==[]:return []block_left=secondList[0][0]block_right=secondList[0][1]second_length=len(secondList)-1first_length=len(firstList)-1second_pointer=0first_pointer=0result_list=[]first_block=firstList[first_pointer]second_block=secondList[second_pointer]while first_pointer<=first_length or second_pointer<=second_length:if first_block[0]>second_block[1]:second_pointer+=1if second_pointer<=second_length: second_block=secondList[second_pointer]else:first_pointer+=1 if first_pointer<=first_length:first_block=firstList[first_pointer]continueif second_block[0]>first_block[1]:first_pointer+=1if first_pointer<=first_length:first_block=firstList[first_pointer]else:second_pointer+=1 if second_pointer<=second_length: second_block=secondList[second_pointer] continue result_list.append([max(first_block[0],second_block[0]),min(first_block[1],second_block[1])])if second_block[1]<=first_block[1]:second_pointer+=1if second_pointer<=second_length: second_block=secondList[second_pointer]else:first_pointer+=1 if first_pointer<=first_length:first_block=firstList[first_pointer]else:first_pointer+=1if first_pointer<=first_length:first_block=firstList[first_pointer] else:second_pointer+=1 if second_pointer<=second_length: second_block=secondList[second_pointer]return result_list
标准解法:
class Solution:def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:length1, length2 = len(firstList), len(secondList)if length1 == 0 or length2 == 0: return []left, right = 0, 0ans = []while left < length1 and right < length2:temp1, temp2 = firstList[left], secondList[right]t_1, t_2 = temp1[0], temp1[1]s_1, s_2 = temp2[0], temp2[1]if t_2 < s_1:left += 1elif t_1 <= s_1 <= t_2:if s_2 < t_2:ans.append(temp2)right += 1elif s_2 == t_2:ans.append(temp2)right += 1left += 1else:ans.append([s_1, t_2])left += 1elif s_1 < t_1 <= s_2:if t_2 < s_2:ans.append(temp1)left += 1elif t_2 == s_2:ans.append(temp1)right += 1left += 1else:ans.append([t_1, s_2])right += 1elif s_2 < t_1:right += 1return ans