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
.代码实现
class Solution:
def combinestr(self,a,b):
i = 0
j = 0
c = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
c.append(int(a[i]))
i += 1
else:
c.append(int(b[j]))
j += 1
while i < len(a):
c.append(int(a[i]))
i += 1
while j < len(b):
c.append(int(b[j]))
j += 1
return c
def change(strings): ##将输入的[1,2,3]变为123
k = 0
strp = ""
strk = "0123456789"
while k < len(strings):
if strings[k] in strk:
strp += strings[k]
k += 1
return strp
if __name__ == "__main__":
A = input()
B = input()
solution = Solution()
str_A = change(A)
str_B = change(B)
print(solution.combinestr(str_A,str_B))
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]