-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajority element II
55 lines (45 loc) · 1.4 KB
/
Majority element II
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
//Majority element II
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while(t-- > 0) {
String s = sc.nextLine();
String[] parts = s.split(" ");
int[] nums = new int[parts.length];
for(int i = 0; i < parts.length; i++) {
nums[i] = Integer.parseInt(parts[i]);
}
Solution ob = new Solution();
List<Integer> ans = ob.findMajority(nums);
if(ans.size() == 0) {
System.out.println("[]");
}
else {
for(int i : ans) {
System.out.print(i + " ");
}
System.out.println();
}
}
sc.close();
}
}
class Solution {
public List<Integer> findMajority(int[] nums) {
List<Integer> ans = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
for(Map.Entry<Integer, Integer> mapEl : map.entrySet()) {
if(mapEl.getValue() > (nums.length / 3)) {
ans.add(mapEl.getKey());
}
}
return ans;
}
}