Lintcode - Majority Number II

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.

Find it.

Note

There is only one majority number in the array

Example

For [1, 2, 1, 2, 1, 3, 3] return 1

Challenge

O(n) time and O(1) space

思路:

1. 选择两个candidate

2.scan数组,如果和两个candidate相等,则相应的candidate count+1;如果不相等,两个candidate 的counter都减1(前提是counter都大于0);如果某一个counter已经等于0,那么替换candidate为当前数

3. 我们最后得到两个candidate,但是不知道谁更majority,因为一个例子就是1,1,1,1,3,3,3,2,2,2,5,5,5,最后candidate1=1, counter=1,candidate2=5,counter2=3,原因就是candidate1在之前被错误的抵消了很多。所以要再扫一遍。

    public int majorityNumber(ArrayList<Integer> nums) {
        int can1 = nums.get(0);
        int count1 = 1;
        int i = 1;
        while (i < nums.size() && nums.get(i) == can1) {
            count1++;
            i++;
        }
        int can2 = 0;
        int count2 = 0;
        if (i < nums.size()) {
            can2 = nums.get(i);
            count2++;
        }
        while (i < nums.size()) {
            int cur = nums.get(i);
            if (cur == can1) {
                count1++;
            } else if (cur == can2) {
                count2++;
            } else { // not match any candidate
                if (count1 == 0) {
                    can1 = cur;
                    count1++;
                } else if (count2 == 0) {
                    can2 = cur;
                    count2++;
                } else {
                    count1--;
                    count2--;
                }
            }
            i++;
        }
        count1 = 0;
        count2 = 0;
        for (int j = 0; j < nums.size(); j++) {
            if (nums.get(j) == can1) {
                count1++;
            }
            if (nums.get(j) == can2) {
                count2++;
            }
        }
        return count1 > count2 ? can1 : can2;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值