Problem

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

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

Follow-up: Could you solve the problem in linear time and in O(1) space?

Solution

Sort and use middle - O(n log n) time - O(1) space

using namespace std;
 
class Solution {
public:
    int majorityElement(vector<int>& nums) {
		sort(begin(nums), end(nums));
		return nums[nums.size() / 2];
    }
};

Hash Table counter - O(n) time - O(n) space

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> m;
        
        for(int i = 0; i < n; i++) {
            m[nums[i]]++;
        }
        n = n/2;
        for(auto x: m){
            if(x.second > n){
                return x.first;
            }
        }
        return 0;
    }
};

Moore’s Voting - O(n) time - O(1) space

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 0;
        int candidate = 0;
        
        for (int num : nums) {
            if (count == 0) candidate = num;
            
            if (num == candidate) count++;
            else count--;
        }
        
        return candidate;
    }
};