-
Notifications
You must be signed in to change notification settings - Fork 17
/
FrequencyOfArrayElements.java
70 lines (68 loc) · 2.01 KB
/
FrequencyOfArrayElements.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
package SummerTrainingGFG.Hashing;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* @author Vishal Singh */
public class FrequencyOfArrayElements {
/**
* Naive Solution
* O(N^2)
* O(1) - Auxiliary space*/
static void frequencyOfArrayElements(int[] arr,int n){
for (int i = 0; i < n; i++) {
boolean flag = false;
for (int j = i-1; j >= 0; j--) {
if (arr[i] == arr[j]){
flag = true;
break;
}
}
if (flag)
continue;
int freq = 1;
for (int j = i+1; j < n; j++) {
if (arr[i] == arr[j]){
freq++;
}
}
System.out.println(arr[i]+"="+freq);
}
}
/**
* Efficient Solution
* O(N)
* O(N) - Aux space*/
static void countFreq(int[] arr,int n){
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i])+1);
}
else {
map.put(arr[i],1);
}
}
System.out.println(map);
}
static void countFrequencyMaintainOrder(int[] arr,int n){
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
if (map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i])+1);
}
else {
map.put(arr[i],1);
}
}
System.out.println(map);
}
public static void main(String[] args) {
int[] arr = {10,12,10,15,10,20,12,12,12};
System.out.println("Naive Solution");
frequencyOfArrayElements(arr,arr.length);
System.out.println("Hash Map No Order: ");
countFreq(arr,arr.length);
System.out.println("Linked Hash Map Same Order");
countFrequencyMaintainOrder(arr,arr.length);
}
}