14.按另外一个数组排序

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

注意点:
1)Counter对象没有sort()方法,可以用sorted()
2)Counter对象的删除:del counter[I] 或 counter.pop(i)
3)temp.sort() a= sorted(temp). 一个默认赋值给本身,一个需要手动赋值

import collections


def solution(l1, l2):
    res = []
    temp = collections.Counter(l1)
    for i in l2:
        if i in temp:
            res += [i] * temp[i]
            #  del temp[i]也可以
            temp.pop(i)
    for j in sorted(temp):
        res += [j] * temp[j]
    return res


if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        l1 = list(map(int, input().strip().split()))
        number1, number2 = l1[0], l1[1]
        l2 = list(map(int, input().strip().split()))
        l3 = list(map(int, input().strip().split()))
        result = solution(l2, l3)
        print(" ".join(map(str, result)))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值