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.
1 | Example 1: |
My solution
Sort the array
We sort the array first in the non-decreasing order.
1 | sort(nums.begin(), nums.end(), [](int & a, int & b){ |
Count the number of each element
Then we loop the array and count how many times one value appears in the array. As the array is sorted already, we just need to check whether the current element is equal to the previous one. If they are equal, we plus 1 to the count, otherwise, we set the count to 0. We also set one variable to store the best count, and another variable to store the value that has the best count. During the loop, we update the best count and the value that has most count.
1 | for (int i = 1; i < nums.size(); i++){ |
Full code
1 | class Solution { |
Improved Solution
ChatGPT provides a better solution:
You can solve this problem in linear time and O(1) space using a well-known algorithm called “Boyer-Moore Majority Vote Algorithm.” This algorithm allows you to find the majority element in an array efficiently.
Here’s the algorithm in C++:
1 | class Solution { |
Compare to my solution, this solution doesn’t sort the array, which save a lot of time. Also, it only have two variables. If the count is not equal to zero, which means the candidate variable is still the majority value. If the count is equal to zero, which means the candidate variable is not the majority value, we update the candidate variable to the current element, and set the count to 1.