zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    Codeforces F. Bits And Pieces(位运算)
    一场comet常规赛的台前幕后
    【NOIP2019模拟2019.9.4】B(期望的线性性)
    「NOI2016」循环之美(小性质+min_25筛)
    【NOI2011】兔农(循环节)
    LOJ #6538. 烷基计数 加强版 加强版(生成函数,burnside引理,多项式牛顿迭代)
    noi2019感想
    7.12模拟T2(套路容斥+多项式求逆)
    CF 848E(动态规划+分治NTT)
    CF 398 E(动态规划)
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7084622.html
Copyright © 2011-2022 走看看