O(n) C solution


  • 7
    T
    int majorityElement(int* nums, int numsSize) {
        int cnt = 1;
        int major = nums[0];
        for(int i = 1; i < numsSize; i++){
            if(nums[i] == major) cnt++;
            else if(cnt == 0){
                major = nums[i];
                cnt++;
           }
           else
               cnt--;
        }
        return major;
    }

  • 0
    R

    nice, I was incorrect this solution does work.


Log in to reply
 

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