Skip to content

Commit 97435a9

Browse files
committed
Solve #229
1 parent 6737705 commit 97435a9

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,4 @@ mod n0225_implement_stack_using_queues;
196196
mod n0226_invert_binary_tree;
197197
mod n0227_basic_calculator_ii;
198198
mod n0228_summary_ranges;
199+
mod n0229_majority_element_ii;

src/n0229_majority_element_ii.rs

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* [229] Majority Element II
3+
*
4+
* Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
5+
*
6+
* Note: The algorithm should run in linear time and in O(1) space.
7+
*
8+
* Example 1:
9+
*
10+
*
11+
* Input: [3,2,3]
12+
* Output: [3]
13+
*
14+
* Example 2:
15+
*
16+
*
17+
* Input: [1,1,1,3,3,2,2,2]
18+
* Output: [1,2]
19+
*
20+
*/
21+
pub struct Solution {}
22+
23+
// submission codes start here
24+
25+
impl Solution {
26+
pub fn majority_element(nums: Vec<i32>) -> Vec<i32> {
27+
if nums.is_empty() { return vec![] }
28+
let (mut vote0, mut vote1, mut candidate0, mut candidate1) = (0, 0, -1, -2);
29+
for &num in nums.iter() {
30+
if num == candidate0 {
31+
vote0 += 1;
32+
} else if num == candidate1 {
33+
vote1 += 1;
34+
} else if vote0 == 0 {
35+
candidate0 = num;
36+
vote0 = 1;
37+
} else if vote1 == 0 {
38+
candidate1 = num;
39+
vote1 = 1;
40+
} else {
41+
vote0 -= 1;
42+
vote1 -= 1;
43+
}
44+
}
45+
// the presents of majority element is not guaranteed, we have to do a double check
46+
let mut res = Vec::new();
47+
for &v in vec![candidate0, candidate1].iter() {
48+
let mut count = 0;
49+
for &num in nums.iter() {
50+
if v == num {
51+
count += 1;
52+
}
53+
}
54+
if count > (nums.len() / 3) as i32 {
55+
res.push(v);
56+
}
57+
}
58+
res
59+
}
60+
}
61+
62+
// submission codes end
63+
64+
#[cfg(test)]
65+
mod tests {
66+
use super::*;
67+
68+
#[test]
69+
fn test_229() {
70+
assert_eq!(Solution::majority_element(vec![1,1,1,2,2,2,3,3,3]), vec![]);
71+
assert_eq!(Solution::majority_element(vec![1,1,1,2,2,3,3,3]), vec![1,3]);
72+
assert_eq!(Solution::majority_element(vec![1]), vec![1]);
73+
assert_eq!(Solution::majority_element(vec![5,6,6]), vec![6]);
74+
assert_eq!(Solution::majority_element(vec![1,2,3,4]), vec![]);
75+
}
76+
}

0 commit comments

Comments
 (0)