Complete the code to initialize the candidate variable for Moore's Voting Algorithm.
int candidate = [1];The candidate is initialized to the first element of the array to start tracking the majority element.
Complete the code to update the count when the current number matches the candidate.
if (nums[i] == candidate) { count [1]; }
When the current number matches the candidate, we increase the count by 1.
Fix the error in updating the candidate when count reaches zero.
if (count == 0) { candidate = [1]; count = 1; }
When count is zero, we update the candidate to the current element nums[i].
Fill both blanks to complete the loop that implements Moore's Voting Algorithm.
for (int i = 1; i [1] nums.length; i++) { if (nums[i] == candidate) { count [2]; } else { count--; } }
The loop runs while i is less than nums.length, and count is incremented when nums[i] equals candidate.
Fill all three blanks to complete the method that returns the majority element using Moore's Voting Algorithm.
public int majorityElement(int[] nums) {
int candidate = [1];
int count = 1;
for (int i = 1; i [2] nums.length; i++) {
if (nums[i] == candidate) {
count[3];
} else {
count--;
if (count == 0) {
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}The candidate starts as nums[0], the loop runs while i < nums.length, and count is incremented with ++.
