20240407 Finished
This commit is contained in:
parent
b81f8aed3d
commit
18604587bd
|
@ -95,3 +95,4 @@ 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 p169_majority_element;
|
40
src/problem/p169_majority_element.rs
Normal file
40
src/problem/p169_majority_element.rs
Normal 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]));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user