【发布时间】:2021-08-27 06:41:09
【问题描述】:
说明:
- 我需要有效地合并两个列表,它们的元素是 serval(至少 10000)次的范围值。如果可以,所有元素都应该合并。
- 两个列表已经排序。
- 每个元素都是严格分开的,这意味着这些情况是非法的:
list1 = [[1, 3], [3, 6]]
list2 = [[1, 4], [2, 5]]
list1 = [[1, 5], [6, 10]]
list2 = [[2, 4], [5, 8]]
示例:
#elements: 0:start(inclusive) 1:stop(inclusive).
#the `ans` become next `list1`, to merge a new `list2` .
#input1:
list1 = [[1, 1],[3, 3]]
list2 = [[5, 5]]
#output1:
ans = [[1, 1], [3, 3], [5, 5]]
#input2:
list1 = [[1, 1], [3, 3], [5, 5]]
list2 = [[2, 2]]
#output2:
ans = [[1, 3], [5, 5]] # [1,1]+[2,2]+[3,3] = [1,3]
#input3:
list1 = [[1, 3], [5, 5]]
list2 = [[0, 0], [4, 4], [6, 6]]
#output:
ans = [[0,6]] #[0,0]+[1,3]+[4,4]+[5,5]+[6,6] = [0,6]
我尝试过的:
def merge(list1,list2):
ans = sorted(list1+list2,key = lambda x:x[0])
idx = 0
while idx<len(ans):
try:
if ans[idx][1] == ans[idx+1][0] - 1:
ans[idx] = [ans[idx][0],ans[idx+1][1]]
del ans[idx+1]
elif ans[idx][0] == ans[idx+1][1] + 1:
ans[idx] = [ans[idx+1][0],ans[idx][1]]
del ans[idx+1]
else:
idx+=1
except Exception:
idx+=1
return ans
- 它可以工作,但速度很慢。解决一个难题大约需要 15 秒,解决一个简单案例大约需要 1.2 秒。
- 解决难题所需的时间少于 3 秒。
问题
- 有更好的解决方案吗?
- 或者我应该使用哪种算法?也许是分段树?
【问题讨论】:
-
这两个列表本身是否已经排序?您的所有示例输入都表明它们是。
-
@schwobaseggl 是的,两个列表已经排序。