Leetcode 169. Majority Element
Given an array nums of size n, return the majority element. The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array.
Given these clarifications, we can proceed to solve the problem.
One efficient method to solve this problem is by using the Boyer-Moore Voting Algorithm. This algorithm works in linear time (O(n)) and constant space (O(1)). The idea behind the algorithm is to maintain a candidate for the majority element and a count that represents how many times we have found the candidate element.
candidate and set count to 1.candidate, increment count.candidate, decrement count.count becomes 0, change the candidate to the current element and reset count to 1.#include <vector>
class Solution {
public:
int majorityElement(std::vector<int>& nums) {
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == candidate) {
count++;
} else {
count--;
}
if (count == 0) {
candidate = nums[i];
count = 1;
}
}
return candidate;
}
};
candidate and count.This solution is optimal for solving the majority element problem under the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?