C++, 2 lines O(n) space and 8 lines O(1) space Boyer-Moore solutions


  • 0

    Solution 1

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

    Solution 2

    Boyer-Moore Majority Vote algorithm.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.