[LintCode] 主元素 II Majority Number II

98 篇文章 0 订阅
4 篇文章 0 订阅

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

注意事项
数组中只有唯一的主元素

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

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

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.

Notice
There is only one majority number in the array.

Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.

Challenge
O(n) time and O(1) extra space.

思路:同时消除三个不一致的数
参考:http://www.cnblogs.com/theskulls/p/4915270.html

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: The majority number that occurs more than 1/3
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        if(nums == null || nums.size() == 0) return 0;
        int candi1 = Integer.MIN_VALUE, count1 = 0;
        int candi2 = Integer.MIN_VALUE, count2 = 0;
        for(int i = 0; i < nums.size(); i++) {
            int temp = nums.get(i);
            if(temp != candi1 && temp != candi2) {
                if(count1 == 0) {
                    candi1 = temp; count1++;
                }else if(count2 == 0) {
                    candi2 = temp; count2++;
                }else{
                    count1--;count2--;
                }
            }else if(temp == candi1) {
                count1++;
            }else{
                count2++;
            }
        }
        count1 = 0; count2 = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(candi1 == nums.get(i))
                count1++;
            else if(candi2 == nums.get(i))
                count2++;
        }
        return count1 > count2 ? candi1 : candi2;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值