请实现一个函数,功能为合并两个升序数组为一个升序数组
输入的格式是用逗号隔开的数字。
数据范围:输入的字符串长度满足
输入有多个测试用例,每个测试用例有1-2行,每行都是以英文逗号分隔从小到大排列的数字
输出一行以英文逗号分隔从小到大排列的数组
1,5,7,9 2,3,4,6,8,10
1,2,3,4,5,6,7,8,9,10
不允许使用原生的 sort、concat 等函数
""" 思路: - 双指针思想 - 额外的空间保存结果,比较指针指向的两数组数字,小的放进额外空间即可 """ import sys inputs = [] for line in sys.stdin: inputs.append(line.strip()) if len(inputs) == 1: print(inputs[0]) else: nums_1 = list(map(int, inputs[0].split(','))) nums_2 = list(map(int, inputs[1].split(','))) res = [] p1, p2 = 0, 0 while p1 < len(nums_1) and p2 < len(nums_2): if nums_1[p1] <= nums_2[p2]: res.append(nums_1[p1]) p1 += 1 else: res.append(nums_2[p2]) p2 += 1 res += nums_1[p1:]+nums_2[p2:] print(','.join(list(map(str, res))))
import sys a=list(map(int,sys.stdin.readline().split(','))) try: b=list(map(int,sys.stdin.readline().split(','))) res=[] l,r=0,0 while l<len(a) and r<len(b): if a[l]<b[r]: res.append(a[l]) l+=1 else: res.append(b[r]) r+=1 if r<len(b): res.extend(b[r:]) else: res.extend(a[l:]) res=list(map(str,res)) print(','.join(res)) except: a=list(map(str,a)) print(','.join(a))
""" 同时遍历两数组,选择较小的值加入新数组 """ import sys if __name__ == "__main__": # sys.stdin = open("input.txt", "r") try: a = list(map(int, input().strip().split(','))) b = list(map(int, input().strip().split(','))) except: b = [] i = j = 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 if c: print(','.join(map(str, c)))