File tree Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public List <Integer > majorityElement (int [] nums ) {
3
+ if (nums .length == 0 ) return Collections .emptyList ();
4
+
5
+ int n1 = nums [0 ];
6
+ int n2 = nums [0 ];
7
+
8
+ int c1 = 0 ;
9
+ int c2 = 0 ;
10
+
11
+ for (int i = 0 ; i < nums .length ; i ++){
12
+
13
+ // put to an empty slot
14
+ if (c1 <= 0 && nums [i ] != n2 ){
15
+ n1 = nums [i ];
16
+ c1 = 1 ;
17
+ continue ;
18
+ }
19
+
20
+ if (c2 <= 0 && nums [i ] != n1 ){
21
+ n2 = nums [i ];
22
+ c2 = 1 ;
23
+ continue ;
24
+ }
25
+
26
+ // add count
27
+ if (nums [i ] == n1 ){
28
+ c1 ++;
29
+ continue ;
30
+ }
31
+
32
+ if (nums [i ] == n2 ){
33
+ c2 ++;
34
+ continue ;
35
+ }
36
+
37
+ // no match
38
+
39
+ c1 --;
40
+ c2 --;
41
+ }
42
+
43
+ // faint
44
+ return new ArrayList <>(IntStream .of (n1 , n2 )
45
+ .filter (n ->
46
+ Arrays .stream (nums ).filter (i -> n == i ).count () > nums .length / 3 )
47
+ .boxed ()
48
+ .collect (Collectors .toSet ()));
49
+ }
50
+ }
Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : solution
3
+ title : Majority Element II
4
+ date : 2015-06-29 13:42:29+08:00
5
+ leetcode_id : 229
6
+ ---
7
+ {% include_relative README.md %}
You can’t perform that action at this time.
0 commit comments