-
Notifications
You must be signed in to change notification settings - Fork 0
/
229.majority-element-ii.java
49 lines (44 loc) · 1.13 KB
/
229.majority-element-ii.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
class Solution {
public List<Integer> majorityElement(int[] nums) {
int num1 = -1;
int num2 = -1;
int count1 = 0;
int count2 = 0;
List<Integer> res = new ArrayList<Integer>();
for(int num: nums){
if(num1 == num)
count1++;
else if(num2 == num){
count2++;
}
else if(count1 == 0)
{
num1 = num;
count1++;
}
else if(count2 == 0){
num2 = num;
count2++;
}
else{
count1--;
count2--;
}
}
System.out.println(num1+" "+num2+" "+count1+" "+count2);
count1 = 0;
count2 = 0;
for(int num: nums){
if(num1 == num)
count1++;
else
if(num2 == num)
count2++;
}
if(count1 > nums.length/3)
res.add(num1);
if(count2 > nums.length/3)
res.add(num2);
return res;
}
}