Skip to content

Instantly share code, notes, and snippets.

@LotusChing
Created July 13, 2016 03:12
Show Gist options
  • Save LotusChing/96736f2bc8981337f4df2b5f72d05ed5 to your computer and use it in GitHub Desktop.
Save LotusChing/96736f2bc8981337f4df2b5f72d05ed5 to your computer and use it in GitHub Desktop.
merge list and keep order
l1 = [2, 4, 6, 8, 9, 10]
l2 = [0, 1, 2, 6, 7, 9, 100, 134]
'''
思路
1. 因为是两个list都是有序列表,所以对比两个列表末尾的元素取出最大值
2. 根据最大值创建一个最大值+1的dict叫做bucket(桶)
3. 合并两个list然后进行循环,根据列表中的元素找到bucket中的key,然后对value+1
4. 最后遍历bucket,取出value不等于0的,然后根据key对应的value循环输出key
'''
def merge(list1, list2):
max_num = [list1[-1] if list1[-1] > list2[-1] else list2[-1]][0]
bucket = {x: 0 for x in range(max_num + 1)}
for k in list1 + list2: bucket[k] += 1
return [k for k in bucket for v in range(bucket[k]) if bucket[k] != 0]
print(merge(l1, l2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment