Given an array of sizen, 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.

这道题既然题里说了一定有这样的majority element,那就用类似投票的方法,把第一个数当做majority element,个数为1,如果遇到不相等的数,个数减一,如果个数已经是0了,就把新的数作为majority element,如果相等的话就把个数加1。这样最终得到的就是majority element

class Solution {
    public int majorityElement(int[] nums) {
        int num = nums[0];
        int count = 1;

        for(int i = 1; i < nums.length; i++) {
            if(nums[i] == num) {
                count++;
            } else {
                if(count == 0) {
                    num = nums[i];
                    count = 1;
                } else {
                    count--;
                }
            }
        }

        return num;
    }
}

results matching ""

    No results matching ""