Complete the code to initialize the candidate variable.
let mut candidate = [1];The candidate starts as 0 to hold the potential majority element.
Complete the code to update the count when the current number matches the candidate.
if num == candidate { count [1] 1; }
We add 1 to count when the current number matches the candidate.
Fix the error in resetting the candidate and count when count reaches zero.
if count == 0 { candidate = [1]; count = [2]; }
When count is zero, we reset candidate to current number and count to 1.
Fill both blanks to correctly decrease count when the current number differs from candidate.
if num != candidate { count [1] 1; }
We subtract 1 from count when the current number is different from candidate.
Fill all three blanks to complete the function that returns the majority element.
fn majority_element(nums: Vec<i32>) -> i32 {
let mut candidate = [1];
let mut count = 0;
for num in nums {
if count == 0 {
candidate = num;
count = [2];
}
if num == candidate {
count [3] 1;
} else {
count -= 1;
}
}
candidate
}The candidate starts at 0, count resets to 1 when candidate changes, and count increases by 1 when num matches candidate.
