[recommend for beginners]clean C++ implementation with detailed explanation


  • 0
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            if(nums.size()==0)  return 0;
            int value=nums[0];
            int count=1;
            for(int i=1; i<nums.size(); i++){
                if(nums[i]==value) count++;
                else count--;
                if(count==0){
                    value=nums[i];
                    count=1;
                }
            }
            return value;
        }
    };

  • 0
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int n=nums.size();
            if(n==0)  return 0;
            if(n==1)  return nums[0];
            
            int result=nums[0];
            int count=1;
            for(int i=1; i<n; i++){
                if(nums[i]==result)  count++;
                else {
                    if(--count==0){
                        result=nums[i];
                        count=1;
                    }
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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