[JAVA] Iterate and count duplicate / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public int majorityElement(int[] nums) {
            int val = 0;
            int count = 0;
            boolean pre = false;
            for(int i = 0; i < nums.length; i+=2){
                if(i+1 >= nums.length || nums[i] == nums[i+1]){
                    if(!pre){
                        val = nums[i];
                        count = 1;
                        pre = true;
                    }
                    else if(val != nums[i]){
                        count--;
                        if(count == 0)
                            pre = false;
                    }
                    else{
                        count++;
                    }
                }
            }
            return val;
        }
    }
    

Log in to reply
 

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