leetcode_Majority Element II

141 篇文章 4 订阅
132 篇文章 1 订阅

描述:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

思路:

1.跟让求一个数组中出现次数超过一半的元素类似,这次让求出现次数超过n/3次数的元素,原则上是类似的,但难度要大好多

2.因为是类似的,所以总体思路应该还是一样的,但具体怎么做呢?这次维护一个curNum1和curNum2两个锚点并用count1和count2来计算锚点出现的次数,因为求超过n/3次数的元素,所以数组中可能存在两个这样的元素,其它的就和Majority Element类似了,只有nums[i]与curNum1和curNum2均不相等时才会count1--,count2--

3.和Majority Element不同,最后剩下的curNum1和curNum2有可能不是出现次数超过n/3的那个数,所以还需要统计下curNum1和curNum2出现的真实次数,但这并不等于说会漏掉出现次数超过n/3的数字

代码:

public List<Integer> majorityElement(int[] nums) {
		List<Integer>list=new ArrayList<Integer>();
		if(nums==null)
			return list;
        int count1=0,curNum1=0;
        int count2=0,curNum2=1;
        for(int num:nums)
        {
        	if(num==curNum1)
        		count1++;
        	else if(num==curNum2)
        		count2++;
        	else if(count1==0)
        	{
        		curNum1=num;
        		count1=1;
        	}else if(count2==0)
        	{
        		curNum2=num;
        		count2=1;
        	}else {
				count1--;
				count2--;
			}
        }
        count1=0;
        count2=0;
        for(int num:nums)
        {
        	if(num==curNum1)
        		count1++;
        	else if(num==curNum2)
        		count2++;
        }
        if(count1>nums.length/3)list.add(curNum1);
        if(count2>nums.length/3)list.add(curNum2);
        return list;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值