My 7 line 16ms counter c++ solution, very easy to understand


  • 1
    Y
    int majorityElement(vector<int>& nums) {
            int count = 1, pre = nums[0];
            for(int i = 1; i < nums.size(); i++){
                if(nums[i] == pre) count++;
                else{
                    count--;
                    if(count <= 0){pre = nums[i]; count = 1;}
                }
            }
            return pre;
        }

Log in to reply
 

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