Friday, April 14, 2017

169. Majority Element


Version #1 Voting Algorithm

36.70%
public class Solution {
    public int majorityElement(int[] nums) {
        if (nums == null || nums.length == 0) throw new IllegalArgumentException();
        int major = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (count == 0) {
                major = nums[i];
                count++;
            } else if (nums[i] == major) count++;
            else count--;
        }
        return major;
    }
}

No comments:

Post a Comment