-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumHashing.java
More file actions
55 lines (40 loc) · 1.51 KB
/
NumHashing.java
File metadata and controls
55 lines (40 loc) · 1.51 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
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class NumHashing {
public static void main(String[] args) {
//CHECKS FREQUENCY OF AN ELEMENT(number) IN AN ARRAY USING HASHMAPS
Scanner scanner = new Scanner(System.in);
int n;
int[] arr;
System.out.print("Enter the size of array (n) : ");
n = scanner.nextInt();
arr = new int[n];
System.out.println("Enter array elements : ");
for (int i = 0; i < n; i++) {
System.out.printf("Element %d : ", i);
arr[i] = scanner.nextInt();
}
// PRECOMPUTING
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
int Q;
System.out.print("\nEnter number of queries : ");
Q = scanner.nextInt();
for (int i = 0; i < Q; i++) {
int num;
System.out.printf("Enter Query %d : ", i);
num = scanner.nextInt();
// FETCHING
System.out.println(num + " appears "+ "->" + " " + map.getOrDefault(num, 0) + " times");
}
//IT'LL ITERATE THROUGH ALL THE ELEMENTS IN THE MAP
System.out.println("\n--- Map Contents ---");
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "->" + entry.getValue());
}
scanner.close();
}
}