My 24ms C++ unordered_map solution.


  • 1
    P
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int size = nums.size();
            if(size == 1) return nums[0];
            
            int half = size/2;
            unordered_map<int, int> map;
            while(size-- >= 0)
                if(map[nums[size]]++ >= half) 
                    return nums[size];  
        }
    };

  • 1
    S

    i use map, 44ms. Of course, in this case, unordered_map is better than map, cause it doesn't need order at all.


Log in to reply
 

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