有位大佬出了一道测试代码能力的编程题:合并两个有序的list为新list并且保证结果有序,不能使用Python或者第三方提供的排序函数,纯手写不能调试,5分钟内完成。
lst1 =[1,3,7,9,10]
lst2=[2,4,8,11]
比较有意思,记录下来。
我当时考虑的比较多,跳出了这两个list。首先想到是先遍历lst1再在循环里面遍历lst2做数字大小比较,这时会遇到比如lst2存在比lst1中最小元素值还小的元素,或者lst2存在比lst1中最中元素值还大的元素应该怎么处理,lst1和lst2存在相同值的元素时应该怎么处理。
当时手撸的还是有不少漏洞,下面是我后来整理的代码,不知道有没更好思路。
代码一:遍历lst2中的元素,找出该元素在lst1中位置并插入
lst1 =[1,3,7,9,10]
lst2=[0,2,3,4,8,11]
i2_max_index = 0
for i2_index, i2_value in enumerate(lst2):
for i1_index, i1_value in enumerate(lst1):
if i2_value <= i1_value:
index = i1_index if i1_index >0 else 0
lst1.insert(index, i2_value)
#记录lst2已追加到lst1的所有元素中的最大位置,便于后续处理此位置之后的元素
i2_max_index = i2_index if i2_index > i2_max_index else i2_max_index
break
#把lst2中超过lst1最大数字的元素追加到lst1尾盘
lst1 += lst2[i2_max_index+1:] if i2_max_index < len(lst2) -1 else []
print(lst1)
心得:时间紧,就要简化任务,两个list中的元素比较通常都是用两个遍历,不调试很容绕晕。
代码二:遍历lst1,再在循环中遍历lst2,把lst2中的元素值比从lst1获取的元素小的元素插入new_list,再把从lst1获取的元素插入new_list,最后把lst2中比lst1最大元素都大的元素追加到new_list,这里我用index做了位置记录,避免再次对lst2全部元素的遍历。
new_list = []
index = 0
for i1_value in lst1:
for i2_value in lst2[index:]:
if i1_value >= i2_value:
index += 1
new_list.append(i2_value)
else:
break
new_list.append(i1_value)
if (index+1 < len(lst2)):
for i2_value in lst2[index+1:]:
new_list.append(i2_value)
print(new_list)
有兴趣的码友可以在评论区交流一下