题解 | #整型数组合并#

整型数组合并

https://www.nowcoder.com/practice/c4f11ea2c886429faf91decfaf6a310b?tpId=37&tqId=21303&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D2%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=2&judgeStatus=undefined&tags=&title=

# -*- coding: utf-8 -*-
"""
@Time    : 2023/5/7 17:02
@Author  : Frank
@File    : HJ80.py

    arr1 = [1, 2, 3, 4, 9]
    arr2 = [3, 4, 5, 9, 19]
    size1 = len(arr1)
    size2 = len(arr2)

"""
from typing import List


def prepare_data():
    size1 = int(input())
    arr = input()
    arrs = [int(num) for num in arr.split()]

    return size1, arrs
    pass


def remove_duplication() -> List:
    size1, arr1 = prepare_data()
    size2, arr2 = prepare_data()

    # print(size1, arr1)
    # print(size2, arr2)
    arr1.sort()
    arr2.sort()

    result = []

    i = 0
    j = 0

    last_idx = -1
    # merge sort
    while i < size1 and j < size2:

        if arr1[i] <= arr2[j]:
            if last_idx >= 0:
                if result[last_idx] != arr1[i]:
                    result.append(arr1[i])
                    last_idx += 1
            else:
                result.append(arr1[i])
                last_idx += 1

            i += 1
        else:
            if last_idx >= 0:
                if result[last_idx] != arr2[j]:
                    result.append(arr2[j])
                    last_idx += 1
            else:
                result.append(arr2[j])
                last_idx += 1

            j += 1

    while i < size1:
        if last_idx >= 0:
            if arr1[i] != result[last_idx]:
                result.append(arr1[i])
                last_idx += 1
        else:
            result.append(arr1[i])
            last_idx += 1

        i += 1

    while j < size2:
        if last_idx >= 0:
            if arr2[j] != result[last_idx]:
                result.append(arr2[j])
                last_idx += 1
                pass
        else:
            result.append(arr2[j])
            last_idx += 1

        j += 1
    return result


if __name__ == "__main__":
    result = remove_duplication()

    result = [str(num) for num in result]
    print("".join(result))
    # print(remove_duplication())

整数去重合并 类似于 merge 两个数组的方式,首先对两个数组进行排序,之后进行merge操作即可, 谁小 谁放进新的数组里, 同时注意 如果有相同的数据(去重操作),直接跳过 不进行合并, 合并的时候 要进行去重操作。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务