Java solution, time O(n), space O(1)


  • 0
    M
    
        public int majorityElement(int[] nums) {
            int times = 1;
            int res = nums[0];
            for(int i=1; i<nums.length; i++){
                if(nums[i]==res){
                    times++;
                    if(times>nums.length/2) break;
                } else {
                    times--;
                    if(times<=0){
                        times = 1;
                        res = nums[i];
                    }
                }
            }
            return res;
        }
    
    

Log in to reply
 

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