Java 9 lines solution 2ms


  • 0
    H
    public class Solution {
        public int majorityElement(int[] nums) {
            int res=nums[0], count=1;
            for(int i=1;i<nums.length;i++){
                if(nums[i]==res) count++;
                else if(--count==0){
                    res=nums[i];
                    count=1;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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