Java O(n) Solution


  • 0
    A
    public int majorityElement(final int[] nums) {
            int candidate = 0, count = 0;
            
            for (int num : nums) {
                if (count == 0) {
                    candidate = num;
                    count = 1;
                } else if (num == candidate) {
                    count++;
                } else {
                    count--;
                }
            }
            
            //we don't need to check whether the count > nums.length/2 
           // as the problem statement says there will always be a majority element.
            return candidate;
        }
    

Log in to reply
 

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