-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajorityElement.java
More file actions
40 lines (37 loc) · 995 Bytes
/
majorityElement.java
File metadata and controls
40 lines (37 loc) · 995 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
import java.util.*;
public class majorityElement{
public static void main(String[] args){
int array[]={2,2,1,1,1,2,2};
int element=majorityElement3(array);
System.out.println("The majority element is:"+element);
}
public static int majorityElement2(int[] nums) {
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
//Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>();
int ret=0;
for (int num: nums) {
if (!myMap.containsKey(num))
myMap.put(num, 1);
else
myMap.put(num, myMap.get(num)+1);
if (myMap.get(num)>nums.length/2) {
ret = num;
break;
}
}
return ret;
}
// Moore voting algorithm
public static int majorityElement3(int[] nums) {
int count=0, ret = 0;
for (int num: nums) {
if (count==0)
ret = num;
if (num!=ret)
count--;
else
count++;
}
return ret;
}
}