[算法]按照另一个数组排序

按照另一个数组排序

题目描述

Description

Given two array A1[] and A2[], sort A1 in such a way that the relative order among the elements will be same as those in A2. For the elements not present in A2. Append them at last in sorted order. It is also given that the number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[] has all distinct elements.

Input:A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} A2[] = {2, 1, 8, 3}Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

Since 2 is present first in A2[], all occurrences of 2s should appear first in A[], then all occurrences 1s as 1 comes after 2 in A[]. Next all occurrences of 8 and then all occurrences of 3. Finally we print all those elements of A1[] that are not present in A2[]

Constraints:1 ≤ T ≤ 501 ≤ M ≤ 501 ≤ N ≤ 10 & N ≤ M1 ≤ A1[i], A2[i] ≤ 1000

Input

The first line of input contains an integer T denoting the number of test cases. The first line of each test case is M and N. M is the number of elements in A1 and N is the number of elements in A2.The second line of each test case contains M elements. The third line of each test case contains N elements.

Output

Print the sorted array according order defined by another array.

Sample Input 1

1
11 4
2 1 2 5 7 1 9 3 6 8 8
2 1 8 3

Sample Output 1

2 2 1 1 8 8 3 5 6 7 9
题目解析

给定数组A,如果出现了数组B中的数字,就按照数组B的顺序排序,

再将剩下的数字排序即可

思路解析
  1. 使用一个Map,把数组B中的所有元素放入(不必使用有序map)
  2. 遍历数组A,计算Map中各个元素的数量,并且将遍历到的元素删除
    1. 这里注意,如果是python,要倒序遍历,如果是java,要使用迭代器的移除方法it.remover(),以免报错
  3. 将数组A剩下的元素排序
  4. 打印结果,要按照数组B的顺序打印Map中的结果,再打印排序后的A
代码实现
if __name__ == '__main__':
    for _ in range(int(input())):
        _ = input()
        arr1 = input().strip().split(" ")
        arr2 = input().strip().split(" ")

        dict2 = {}
        for i in arr2:
            dict2[i] = 0

        keys = dict2.keys()
        for i in range(len(arr1) - 1, -1, -1):  # 逆序遍历
            if arr1[i] in keys:
                dict2[arr1[i]] += 1
                del arr1[i]  # 删除 用del更快
        res = []
        for x in arr2:
            for _ in range(dict2[x]):
                res.append(x)
        arr1.sort()
        res = res + arr1
        # print(res)
        print(" ".join(res))
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值