lintcode-47-主元素 II

47-主元素 II

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

注意事项

数组中只有唯一的主元素

样例

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

挑战

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

标签

LintCode 版权所有 枚举法 贪心 Zenefits

思路

参考资料
本题可以一般化为求出数组中出现次数大于数组长度1/k的主元素,本题k=3。若数组长度为n,主元素次数为x,即
x / n > 1 / k
两边同时-1,化简为
(x - 1) / (n - k) > 1/ k
可表示为:若主元素个数-1,同时数组个数-k时,主元素不会被改变。
于是,可得出如下步骤:

  1. 首先遍历数组,建立一个键为数组中元素,值为当前元素出现次数的hash表
  2. 当hash表的大小小于k时,继续步骤1;否则继续步骤3
  3. 对现在hash表中的所有键的值减1
  4. 从hash表中剔除值为0的键值对
  5. 持续进行以上步骤,直到所有数组元素全部被遍历完。
  6. 对现在得到的这个hash表的值归0,
  7. 遍历数组,统计现在hash表中的元素的个数,返回个数最多的那个元素,即主元素。
code
class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number occurs more than 1/3.
     */
    int majorityNumber(vector<int> nums) {
        // write your code here
        int size = nums.size(), hashMaxSize = 3, i = 0;
        map<int, int> hashMap;
        map<int, int>::iterator it;
        int result = 0, maxCount = 0;
        
        for(i=0; i<size; i++) {
            if(hashMap.size() < hashMaxSize) {
                it = hashMap.find(nums[i]);
                if(it == hashMap.end()) {
                    hashMap.insert(pair<int, int>(nums[i], 1));
                }
                else {
                    (it->second)++;
                }
            }
            else {
                for(it=hashMap.begin(); it!=hashMap.end(); it++) {
                    (it->second)--;
                }
                for(it=hashMap.begin(); it!=hashMap.end();) {
                    if(it->second == 0) {
                        hashMap.erase(it++);
                    }
                    else {
                        it++;
                    }
                }
            }
        }

        for(it=hashMap.begin(); it!=hashMap.end(); it++) {
            it->second = 0;
        }

        for(i=0; i<size; i++) {
            it = hashMap.find(nums[i]);
            if(it != hashMap.end()) {
                it->second++;
                if(maxCount < it->second) {
                    maxCount = it->second;
                    result = it->first;
                }
            }
        }
        return result;
    }
};

转载于:https://www.cnblogs.com/libaoquan/p/7084622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值