MajorityElement

问题描述:一个数组中,寻找出现次数大于数组长度一半的元素。假设这个元素一定存在。


解决:可以使用map来存储数据,key为元素的值,value为元素出现的次数。这种方式比较容易想到,是可行的。但是有一种更好的算法叫做Moore's voting。

它的思想是:数组中每出现一对不同的元素就将这对元素从数组中删除,如果元素e出现次数过半,那么最后数组中肯定只剩下e这种元素。当然,并不是

数组中最后剩余的元素一定是出现次数过半的,只是因为本题中已经假设了过半元素一定存在,那么我们只需要把这个元素找出来即可。majority指定为

第0个元素,count初始值为1,当遇到与majority相同元素时,count++,遇到不同元素时,count--。当count=0时,表明前面的元素成对不同需要删去

(一半是majority,一半是其他元素),我们这里并不是还要做删除数组元素的操作,而是将majority重新指定为当前的元素,count重新置1,对剩余

的数组元素做相同操作(其实就是原问题的子问题)。



/*
 * 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.
 */
 
public class MajorityElement {
        public int majorityElement(int[] nums) {
                int count=1;
                int majority = nums[0];
                for(int i=1; i<nums.length; i++) {
                        if(nums[i]==majority) 
                                count++;
                        else 
                                count--;
                        if(count==0) {
                                majority = nums[i];
                                count++;
                        }
                }
                return majority;
        }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值