-
Notifications
You must be signed in to change notification settings - Fork 0
/
day18_5.java
100 lines (76 loc) · 2.17 KB
/
day18_5.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Given two integer arrays A1[ ] and A2[ ] of size N and M respectively. Sort the first array A1[ ] such that all the relative positions of the elements in the first array are the same as the elements in the second array A2[ ].
See example for better understanding.
Note: If elements are repeated in the second array, consider their first occurance only.
Example 1:
Input:
N = 11
M = 4
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Output:
2 2 1 1 8 8 3 5 6 7 9
Explanation: Array elements of A1[] are
sorted according to A2[]. So 2 comes first
then 1 comes, then comes 8, then finally 3
comes, now we append remaining elements in
sorted order.
*/
class Solution{
// 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.
public static int[] sortA1ByA2(int A1[], int N, int A2[], int M)
{
//Your code here
Arrays.sort(A1);
int[] ans = new int[N];
ArrayList<Integer> a = new ArrayList<>();
for(int i=0; i<N; i++)
{
a.add(A1[i]);
}
int k=0;
for(int i=0; i<M ; i++)
{
int y = Collections.binarySearch(a,A2[i]);
while(y>-1)
{
ans[k++]= A2[i];
a.remove(y);
y = Collections.binarySearch(a,A2[i]);
}
}
for(int i=N-a.size(), j=0; i<N; i++, j++)
{
ans[i] = a.get(j);
}
return ans;
}
}
//{ Driver Code Starts.
class Main {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
int a1[]=new int[n];
int a2[]=new int[m];
for(int i=0;i<n;i++)
a1[i]=sc.nextInt();
for(int i=0;i<m;i++)
a2[i]=sc.nextInt();
Solution ob=new Solution();
a1 = ob.sortA1ByA2(a1,n,a2,m);
for(int x:a1)
System.out.print(x+" ");
System.out.println();
}
}
}
// } Driver Code Ends