LeetCode169:求众数之摩尔投票法

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/ASN_forever/article/details/84851711

 

这道题目对众数有了自己的定义,即出现次数大于n/2的元素,而不是出现次数最多的元素。下面这个方法,要求数组中必须有一个元素出现的次数大于等于n/2(前提条件),不然求出的结果不一定是众数。

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

猜你喜欢

转载自blog.csdn.net/ASN_forever/article/details/84851711