O(n) time JS solution


  • 0
    C

    /**

    • @param {number[]} nums
    • @return {number}
      */
      var majorityElement = function(nums) {
      var count=1;
      var maj;
      maj=nums[0];
      for(var i=1;i<nums.length;i++){
      if(nums[i]==maj){
      count++;
      }
      else if(count>0){
      count--;
      }
      else if(count===0){
      maj=nums[i];
      count=1;
      }
      }
      return maj;
      };

Log in to reply
 

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