2. 合并排序数组
1.问题描述
合并两个升序的整数数组A和B,形成一个新的数组,新数组也要有序
2.问题实例:
输入A=[1],B=[1],输出[1, 1],返回合并后的数组。输入A = [1, 2, 3, 4],B=[2, 4, 5, 6],输出[1, 2, 2, 3, 4, 4, 5, 6],饭后合并所有元素后的数组。
3.代码实现
3.1方案一:
class Solution:
def mergeSortedArray(self, A, B):
A.extend(B)
A.sort()
return A
if __name__ == '__main__':
A = [1,4]
B = [1,2,3]
D = [1,2,3,4]
E = [2,4,5,6]
solution = Solution()
print("输入:", A, " ", B)
print("输出:", solution.mergeSortedArray(A, B))
print("输入:", D, " ", E)
print("输出:", solution.mergeSortedArray(D, E))'''
3.2 方案2
class Solution():
#参数A:有序整数数组A
#参数B: 有序整数数组B
#返回: 一个新的有序整数数组
def mergeSort(self, A, B):
i, j = 0, 0
C = []
while i < len(A) and j < len(B):
if A[i] < B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1
while i < len(A):
C.append(A[i])
i += 1
while j < len(B):
C.append(B[j])
j += 1
return C
if __name__ == '__main__':
A = [1, 4]
B = [1, 2, 3]
D = [1, 2, 3, 4]
E = [2, 4, 5, 6]
solution = Solution()
print("输入:", A, " ", B)
print("输出:", solution.mergeSort(A, B))
print("输入:", D, "", E)
print("输出:", solution.mergeSort(D, E))
4.运行结果
输入: [1, 4] [1, 2, 3]
输出: [1, 1, 2, 3, 4]
输入: [1, 2, 3, 4] [2, 4, 5, 6]
输出: [1, 2, 2, 3, 4, 4, 5, 6]