-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion229.java
More file actions
45 lines (37 loc) · 845 Bytes
/
Copy pathQuestion229.java
File metadata and controls
45 lines (37 loc) · 845 Bytes
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
/*
Author: Ananthanarayanan R
Section: Algorithms
Question : 229
*/
import java.util.*;
public class Question229
{
public static List<Integer> majorityElement(int[] nums)
{
Map<Integer,Integer> map = new HashMap<>();
Integer oldVal;
for(int num:nums)
if((oldVal= map.put(num,1)) !=null)
map.put(num,oldVal+1);
List<Integer> result = new ArrayList<>();
int count = 0;
int threshold = (int)Math.floor(nums.length/3);
for(Map.Entry<Integer,Integer> entry : map.entrySet())
{
if(entry.getValue()>threshold)
{
count++;
result.add(entry.getKey());
}
if(count==2)
break;
}
return result;
}
public static void main(String[] args)
{
int[] nums = {1,2};
List<Integer> result = majorityElement(nums);
System.out.println(result);
}
}