-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashing.java
45 lines (37 loc) · 1.12 KB
/
Hashing.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
import java.util.*;
class Hashing{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
//precompute:
HashMap<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < n; i++) {
int key = arr[i];
int freq = 0;
if (mp.containsKey(key))
freq = mp.get(key); // fetching from the map
freq++;
mp.put(key, freq); // inserting into the map
}
// Iterate over the map:
for (Map.Entry<Integer, Integer> it : mp.entrySet()) {
System.out.println(it.getKey() + "->" + it.getValue());
}
int q;
q = sc.nextInt();
while (q-- > 0) {
int number;
number = sc.nextInt();
// fetch:
if (mp.containsKey(number))
System.out.println(mp.get(number));
else
System.out.println(0);
}
}
}