File tree 1 file changed +38
-0
lines changed
solution/0229.Majority Element II
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public List <Integer > majorityElement (int [] nums ) {
3
+ int [] candidate = new int [2 ];
4
+ int [] cnt = new int [2 ];
5
+ for (int num : nums ) {
6
+ if (num == candidate [0 ]) {
7
+ ++cnt [0 ];
8
+ } else if (num == candidate [1 ]) {
9
+ ++cnt [1 ];
10
+ } else if (cnt [0 ] == 0 ) {
11
+ candidate [0 ] = num ;
12
+ cnt [0 ] = 1 ;
13
+ } else if (cnt [1 ] == 0 ) {
14
+ candidate [1 ] = num ;
15
+ cnt [1 ] = 1 ;
16
+ } else {
17
+ --cnt [0 ];
18
+ --cnt [1 ];
19
+ }
20
+ }
21
+ Arrays .fill (cnt , 0 );
22
+ for (int num : nums ) {
23
+ if (num == candidate [0 ]) {
24
+ ++cnt [0 ];
25
+ } else if (num == candidate [1 ]) {
26
+ ++cnt [1 ];
27
+ }
28
+ }
29
+ List <Integer > res = new ArrayList <>();
30
+ if (cnt [0 ] > nums .length / 3 ) {
31
+ res .add (candidate [0 ]);
32
+ }
33
+ if (cnt [1 ] > nums .length / 3 ) {
34
+ res .add (candidate [1 ]);
35
+ }
36
+ return res ;
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments