diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 60e3f88..39b6d5f 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -94,4 +94,5 @@ mod p331_verify_preorder_serialization_of_a_binary_tree; mod p88_merge_sorted_array; mod p26_remove_duplicates_from_sorted_array; mod p27_remove_element; -mod p80_remove_duplicates_from_sorted_array_ii; \ No newline at end of file +mod p80_remove_duplicates_from_sorted_array_ii; +mod p169_majority_element; \ No newline at end of file diff --git a/src/problem/p169_majority_element.rs b/src/problem/p169_majority_element.rs new file mode 100644 index 0000000..7798e0a --- /dev/null +++ b/src/problem/p169_majority_element.rs @@ -0,0 +1,40 @@ +/** + * [169] Majority Element + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn majority_element(nums: Vec) -> i32 { + let mut count = 0; + let mut candidate = nums[0]; + + for i in nums { + if count == 0 { + candidate = i; + } + + count += if candidate == i { + 1 + } else { + -1 + }; + } + + candidate + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_169() { + assert_eq!(3, Solution::majority_element(vec![3,2,3])); + } +}