Another algorithm similar to Moore's


  • 0
    L

    I think it should be same as Moore's voting algorithm in nature.

    class Solution {
        public int majorityElement(int[] nums) {
            int major = nums[0];
            int count = 0;
            for (int i = 0; i < nums.length / 2 * 2; i += 2) {
                if (nums[i] == nums[i + 1]) {
                    count += count > 0 && major != nums[i] ? -1 : 1;
                }
                if (count == 0)
                    major = nums[i + 2];
            }
            return major;
        }
    }
    

Log in to reply
 

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