LeetCode 169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

解法:三国杀理论,假设各方(除了大于n/2的数以外的各种不同的数)群起攻击我方(大于n/2的数),就算我们忽略各方的内战,那么最后剩下的一定还是我。如果不忽略对方的内战则会剩下更多的我方,因此,我们每次遇到新的数字,就将原来的减一,或者前者减到0就换数值为新的数字。等到iterate完数组,得到的结果数字一定是majority element.
    public int majorityElement(int[] nums) {
        if (nums.length == 1) return nums[0];
        int num = nums[0];
        int count = 1;
        for (int i =1; i < nums.length; i++) {
            if (nums[i] == num) {
                count++;
            } else {
                count--;
                if (count == 0) {
                    num = nums[i];
                    count = 1;
                }
            }
        }
        return num;
    }
阅读更多

没有更多推荐了,返回首页