Standard Java implementation of "Boyer-Moore majority vote algorithm"


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

Log in to reply
 

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