LintCode Majority Number 主元素

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

样例
给出数组[1,1,1,1,2,2,2],返回 1

挑战
要求时间复杂度为O(n),空间复杂度为O(1)

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
     //法一:O(32n)位操作。统计32位每一位1的个数多还是0的个数多,取个数多的为该位结果值。
    public int majorityNumber(ArrayList<Integer> nums) {
        int bit = 1;
        int result = 0;
        for(int i = 0; i < 32; i++) {
            int count0 = 0;
            int count1 = 0;
            for(int j = 0; j < nums.size(); j++) {
                if((nums.get(j) & bit) == bit) {//第i位为1
                    count1++;
                }else {//第i位为0
                    count0++;
                }
            }
            if(count0 < count1){//第i位1的数目多于0的数目,则该位应为1,否则为0
                result = result ^ bit;
            }
            bit = bit<<1;
        }
        return result;
    }

    //法二: 分治法 Divide and conquer O(n)
    //保持两个标记变量。一个统计值count初始为0,一个当前值cur。遍历整个数组,用x表示当前值。
    //当count == 0时,设cur = x, count++。
    //当count != 0时,若x == cur,则count++;若x != cur,则count--。
    //最后返回cur。
    public int majorityNumber(ArrayList<Integer> nums) {
        int count = 0;
        int cur = nums.get(0);
        for(int i = 0; i < nums.size(); i++) {
            if(count == 0) {
                cur = nums.get(i);
                count = 1;
            }else {
                if(cur == nums.get(i)) {
                    count++;
                }else{
                    count--;
                }
            }
        }
        return cur;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值