forked from SR-Sunny-Raj/Hacktoberfest2021-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortanArrayAcoordingToOther.cpp
83 lines (62 loc) · 1.4 KB
/
SortanArrayAcoordingToOther.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template in C++
class Solution{
public:
// A1[] : the input array-1
// N : size of the array A1[]
// A2[] : the input array-2
// M : size of the array A2[]
//Function to sort an array according to the other array.
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M)
{
//Your code here
map<int, int> m;
vector<int> v;
for(int i=0;i<N;i++)
m[A1[i]]++;
for(int i=0;i<M;i++)
{
if(m.find(A2[i])!=m.end())
{
while(m[A2[i]]--)
v.push_back(A2[i]);
m.erase(A2[i]);
}
}
for(auto i:m)
{
while(i.second--)
v.push_back(i.first);
m.erase(i.first);
}
return v;
}
};
// { Driver Code Starts.
int main(int argc, char *argv[])
{
int t;
cin >> t;
while(t--){
int n, m;
cin >> n >> m;
vector<int> a1(n);
vector<int> a2(m);
for(int i = 0;i<n;i++){
cin >> a1[i];
}
for(int i = 0;i<m;i++){
cin >> a2[i];
}
Solution ob;
a1 = ob.sortA1ByA2(a1, n, a2, m);
for (int i = 0; i < n; i++)
cout<<a1[i]<<" ";
cout << endl;
}
return 0;
}
// } Driver Code Ends