Moore's Voting Algorithm


  • 10
    N
    public class Solution {
        public int majorityElement(int[] nums) {
            int count = 0;
            int majorityElement = nums[0];
            for(int x:nums){
                if(x!=majorityElement){
                    count--;
                }
                else{
                    count++;
                }
                  if(count==0){
                    majorityElement= x;
                    count=1;
                }
            }
            return majorityElement;
        }
    }

  • 0
    Z

    the string [1 2 3 3 2 2] is worng answer


  • 0
    P

    [1 2 3 3 2 2] is wrong test case since problem description says: "majority element always exist". There is no majority element in you sequence.

    Boyer–Moore majority vote algorithm has two steps: 1) find candidate, 2) Determine if the
    candidate element is a valid majority element. For this problem there is no need to verify candidate element since "majority element always exist" .


  • 0
    Z

    I got it .Thank you!!!


  • -1
    A

    what about this seq {1,4,1,2,1,3,1,3,5,1,6,7}


Log in to reply
 

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