java O(n) solution


  • 0
    A

    class Solution {
    public int majorityElement(int[] nums) {
    int majorityNum = nums[0];
    int count = 1;
    for(int i=1;i<nums.length;i++){
    if(count == 0){
    //when count = 0; assume a new majority num,and set count to be 1
    majorityNum = nums[i];
    count = 1;
    continue;
    }
    if(nums[i]==majorityNum){
    count ++;
    }else{
    count --;
    }
    }
    return majorityNum;
    }
    }


Log in to reply
 

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