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.
Example 1:
Input: nums = [3,2,3] Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Solution 1
class Solution {
public:
int majorityElement(vector<int>& nums) {
// First approach - sort the array and return the mid element
sort(nums.begin(), nums.end());
int mid = nums.size()/2;
return nums[mid];
}
};
Solution 2
class Solution {
public:
int majorityElement(vector<int>& nums) {
// optimized approach without sorting - moore voting algorithm
int count = 0;
int num = 0;
for(int i=0; i<nums.size(); i++) {
if(count == 0) {
num = nums[i];
}
if(num == nums[i]) {
count++;
} else {
count--;
}
}
return num;
}
};