牛客网学习笔记(HJ80整型数组合并)

284 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

题目来自牛客网的华为机试题库,本题目为简单题

HJ80 整型数组合并

描述 题目标题: 将两个整型数组按照升序合并,并且过滤掉重复数组元素。 输出时相邻两数之间没有空格。

输入描述: 输入说明,按下列顺序输入: 1 输入第一个数组的个数 2 输入第一个数组的数值 3 输入第二个数组的个数 4 输入第二个数组的数值 输出描述: 输出合并之后的数组

示例1

输入:
		3
		1 2 5
		4
		-1 0 3 2
输出:
		-101235

我写的,明明用了排序函数,为啥不直接合并之后排序

n = int(input())-1
a = list(map(int,input().split()))
m = int(input())-1
b = list(map(int,input().split()))
a.sort()
b.sort()
re = []
i = j =0
while i <= n and j <= m:
        if a[i] <= b[j]:
            if a[i] not in re:
                re.append(a[i])
            i += 1
        else:
            if b[j] not in re:
                re.append(b[j])
            j += 1
if i > n:
    for r in b[j:]:
        if r not in re:
            re.append(r)
if j > m:
    for r in a[i:]:
        if r not in re:
            re.append(r)
re = [str(x) for x in re]
print(''.join(re))

用set()去重

while True:
    try:
        first_num = int(input())
        first_list = list(map(int, input().split(" ")))
        second_num = int(input())
        second_list = list(map(int, input().split(" ")))
         
        total_list = first_list + second_list
        total_list = list(set(total_list))
        total_list.sort()
        res = ''.join(list(map(str, total_list)))
        print(res)
    except EOFError:
        break

解析

第一个方法是我自己写的笨方法,简单粗暴非常好理解,直接对两个输入分别用sort排序,然后把他们按顺序不重复的保存到re里,为了保证按顺序用了while循环和if语句,虽然想法很简单粗暴,但是实现起来的代码比较复杂,还要考虑结束条件什么的。

我写的方法通过之后,又看了别人的写法。直接用list(set())把两个输入变成不重复的数列,然后sort排序,最后join输出,就很简单,显得第一种方法跟低级了