20240407 Finished

This commit is contained in:
jackfiled 2024-04-07 11:35:33 +08:00
parent b81f8aed3d
commit 18604587bd
2 changed files with 42 additions and 1 deletions

View File

@ -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;
mod p80_remove_duplicates_from_sorted_array_ii;
mod p169_majority_element;

View File

@ -0,0 +1,40 @@
/**
* [169] Majority Element
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> 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]));
}
}