-
Notifications
You must be signed in to change notification settings - Fork 1
/
majorityelmpart2.java
71 lines (53 loc) · 1.79 KB
/
majorityelmpart2.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
package aryanhere.Striver;
import java.util.ArrayList;
import java.util.HashMap;
public class majorityelmpart2 {
public static ArrayList<Integer> majorityelm2(int arr[]) {
int n = arr.length;
ArrayList<Integer> ls = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
if (!ls.contains(arr[i])) {
int cnt = 0;
for (int j = 0; j < n; j++) {
if (arr[j] == arr[i]) {
cnt++;
}
}
if (cnt > n / 3) {
ls.add(arr[i]);
}
}
if (ls.size() == 2) {
break;
}
}
return ls;
}
//traversing with two loops so its O(N^2)
public static ArrayList<Integer> majorityelement3(int arr[]) {
int n = arr.length;
ArrayList<Integer> lst = new ArrayList<>(n);
// declaring this arraylist to store th valu..!
HashMap<Integer, Integer> map = new HashMap<>(n);
/// hashmap to count the occurences of the elm if they are greater thn min thn retrning them..!
int min = (int) (n / 3) + 1;
for (int i = 0; i < n; i++) {
int value = map.getOrDefault(arr[i], 0);
map.put(arr[i], value + 1);
if (map.get(arr[i]) == min) {
lst.add(arr[i]);
}
if (lst.size() == 2) {
break;
}
}
return lst;
}
public static void main(String[] args){
int arr[] = {22 , 22 , 5, 6 , 22 , 7 , 8 , 22 , 22};
ArrayList<Integer> ans = majorityelement3(arr);
for(int i = 0 ; i < ans.size() ; i++){
System.out.println(ans.get(i) + " ");
}
}
}