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

按照另一个数组排序

题目描述

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

扫描二维码关注公众号,回复: 10537071 查看本文章
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))
发布了71 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33935895/article/details/103316832