forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelative-Sorting
More file actions
63 lines (56 loc) · 2.13 KB
/
Relative-Sorting
File metadata and controls
63 lines (56 loc) · 2.13 KB
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
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
while(t-- > 0)
{
String s[] = bf.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
s = bf.readLine().trim().split(" ");
int arr1[] = new int[n];
for(int i=0 ; i<n ; i++)
{
arr1[i] = Integer.parseInt(s[i]);
if(!hm.containsKey(arr1[i]))
hm.put(arr1[i], 1);
else
hm.put(arr1[i], hm.get(arr1[i]) + 1);
}
s = bf.readLine().trim().split(" ");
int arr2[] = new int[m];
for(int i=0 ; i<m ; i++)
arr2[i] = Integer.parseInt(s[i]);
StringBuffer sb = new StringBuffer();
for(int i=0 ; i<m ; i++)
{
if(hm.containsKey(arr2[i]))
{
for(int j=0 ; j<hm.get(arr2[i]) ; j++)
sb.append(arr2[i] + " ");
hm.remove(arr2[i]);
}
}
LinkedList<Map.Entry<Integer, Integer>> list = new LinkedList<Map.Entry<Integer, Integer>>(hm.entrySet());
Comparator<Map.Entry<Integer, Integer>> comp = new Comparator<Map.Entry<Integer, Integer>>(){
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)
{
return o1.getKey() - o2.getKey();
}
};
Collections.sort(list, comp);
for(Map.Entry<Integer, Integer> me : list)
{
for(int i=0 ; i<me.getValue() ; i++)
sb.append(me.getKey() + " ");
}
System.out.println(sb);
}
}
}