13
13
// Output: [1, 2]
14
14
15
15
16
- // 1) Map
16
+ // 1) O(n^2)
17
+
18
+
19
+ // 2) Map
17
20
// 时间复杂度 O(n),空间复杂度 O(n)
18
21
/**
19
22
* @param {number[] } nums
@@ -36,4 +39,49 @@ const majorityElement = (nums) => {
36
39
return res
37
40
}
38
41
// Runtime: 68 ms, faster than 37.98% of JavaScript online submissions for Majority Element II.
39
- // Memory Usage: 37.3 MB, less than 14.29 % of JavaScript online submissions for Majority Element II.
42
+ // Memory Usage: 37.3 MB, less than 14.29 % of JavaScript online submissions for Majority Element II.
43
+
44
+
45
+ // 3) Boyer-Moore Vote algorithm
46
+ // 时间复杂度 O(n),空间复杂度 O(1)
47
+ // similar to 0169
48
+ // 大于 ⌊ n/3 ⌋,分析问题发现,最多出现两个符合条件的元素。设置两个候选。
49
+ /**
50
+ * @param {number[] } nums
51
+ * @return {number[] }
52
+ */
53
+ const majorityElement = ( nums ) => {
54
+ let candidate1 = - 1
55
+ let candidate2 = - 1
56
+ let count1 = 0
57
+ let count2 = 0
58
+ let res = [ ]
59
+ for ( num of nums ) {
60
+ if ( count1 === 0 && num !== candidate2 ) {
61
+ candidate1 = num
62
+ } else if ( count2 === 0 && num !== candidate1 ) {
63
+ candidate2 = num
64
+ }
65
+ if ( num === candidate1 ) {
66
+ count1 ++
67
+ } else if ( num === candidate2 ) {
68
+ count2 ++
69
+ } else {
70
+ count1 --
71
+ count2 --
72
+ }
73
+ }
74
+ const counts = ( arr , value ) => {
75
+ return arr . reduce ( ( a , v ) =>
76
+ v === value ? a + 1 : a + 0 , 0
77
+ )
78
+ }
79
+ for ( let candidate of [ candidate1 , candidate2 ] ) {
80
+ if ( counts ( nums , candidate ) > nums . length / 3 ) {
81
+ res . push ( candidate )
82
+ }
83
+ }
84
+ return res
85
+ }
86
+ // Runtime: 64 ms, faster than 55.37% of JavaScript online submissions for Majority Element II.
87
+ // Memory Usage: 37 MB, less than 14.29 % of JavaScript online submissions for Majority Element II.
0 commit comments