LintCode算法题库第六题:合并有序数组
我们用两种方法实现
方案1:直接合并两个数组,用sorted方法自动排序
时间复杂度:O(1)
Python代码:
class Solution:
"""
@param a: sorted integer array A
@param b: sorted integer array B
@return: A new sorted integer array
"""
def merge_sorted_array(self, a, b):
# write your code here
return sorted(a+b)
方案2:通过同时获取两个数组中的元素,将更小的一方添加到结果中进行合并
Python代码:
class Solution:
"""
@param a: sorted integer array A
@param b: sorted integer array B
@return: A new sorted integer array
"""
def merge_sorted_array(self, a, b):
# write your code here
i1,i2=0,0
result=[]
while i1<len(a) or i2<len(b):
if i1==len(a):
result.append(b[i2])
i2+=1
elif i2==len(b):
result.append(a[i1])
i1+=1
elif a[i1]<b[i2]:
result.append(a[i1])
i1+=1
else:
result.append(b[i2])
i2+=1
return result
本文介绍了两种方法解决LintCode题目——合并两个已排序的整数数组:一种利用Python内置排序功能,另一种通过双指针技巧逐个比较添加。对比了它们的时间复杂度和代码实现细节。
2144

被折叠的 条评论
为什么被折叠?



