原文:
给定两个数组 a1[]和 a2[],以这样一种方式打印 a1 的元素,即元素之间的相对顺序与 a2 中的顺序相同。也就是说,数组 a2[]中位于前面的元素首先从数组 a1[]中打印这些元素。对于 a2 中没有的元素,最后按排序顺序打印出来。 还给出 a2[]中的元素个数小于或等于 a1[]中的元素个数,a2[]具有所有不同的元素。 例:
输入: a1[] = {2,1,2,5,7,1,9,3,6,8,8} a2[] = {2,1,8,3 } t4】输出:2 1 8 8 3 5 6 7 9 t7】输入: a1[] = {2,1,2,5,7,1,9,3,6,8,8} a2[] = {1,10,11}
简单方法:我们创建一个临时数组和一个访问数组,其中临时数组用于将 a1[]的内容复制到其中,访问数组用于标记临时数组中复制到 a1[]的那些元素。然后对临时数组进行排序,并对 a1[]中 a2[]的每个元素进行二分搜索法运算。你可以在这里找到pg电子试玩链接的解决方案
c
// a c program to print an array according
// to the order defined by another array
#include
using namespace std;
// function to print an array according
// to the order defined by another array
void print_in_order(int a1[], int a2[], int n, int m)
{
// declaring map and iterator
map mp;
map::iterator itr;
// store the frequency of each
// number of a1[] int the map
for (int i = 0; i < n; i )
mp[a1[i]] ;
// traverse through a2[]
for (int i = 0; i < m; i ) {
// check whether number
// is present in map or not
if (mp.find(a2[i]) != mp.end()) {
itr = mp.find(a2[i]);
// print that number that
// many times of its frequency
for (int j = 0; j < itr->second; j )
cout << itr->first << " ";
mp.erase(a2[i]);
}
}
// print those numbers that are not
// present in a2[]
for (itr = mp.begin(); itr != mp.end(); itr ) {
for (int j = 0; j < itr->second; j )
cout << itr->first << " ";
}
cout << endl;
}
// driver code
int main()
{
int a1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
int a2[] = { 2, 1, 8, 3 };
int n = sizeof(a1) / sizeof(a1[0]);
int m = sizeof(a2) / sizeof(a2[0]);
print_in_order(a1, a2, n, m);
return 0;
}
python 3
# a python3 program to print an array according
# to the order defined by another array
# function to print an array according
# to the order defined by another array
def print_in_order(a1, a2, n, m) :
# declaring map and iterator
mp = dict.fromkeys(a1,0);
# store the frequency of each
# number of a1[] int the map
for i in range(n) :
mp[a1[i]] = 1;
# traverse through a2[]
for i in range(m) :
# check whether number
# is present in map or not
if a2[i] in mp.keys() :
# print that number that
# many times of its frequency
for j in range(mp[a2[i]]) :
print(a2[i],end=" ");
del(mp[a2[i]]);
# print those numbers that are not
# present in a2[]
for key,value in mp.items() :
for j in range(value) :
print(key,end=" ");
print();
# driver code
if __name__ == "__main__" :
a1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];
a2 = [ 2, 1, 8, 3 ];
n =len(a1);
m = len(a2);
print_in_order(a1, a2, n, m);
# this code is contributed by ankitrai01
output:
2 2 1 1 8 8 3 5 6 7 9
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处