zoukankan      html  css  js  c++  java
  • LintCode "Majority Number III"

    Based on Bucketing and "Majority Number I".

    class Solution {
        pair<int,int> majorityNumber0(vector<int> &num) {
            int count = 0;
            int ret = 0;
            for(int i = 0; i < num.size(); i ++)
            {
                if (count == 0)
                {
                    ret = num[i];
                    count = 1;
                    continue;
                }
                if(ret != num[i]) count --;
                else if(ret == num[i]) count ++;
            }
            // find count
            int cnt = 0;
            for(auto v: num)
                if(v == ret) cnt ++;
            return make_pair(ret, cnt);
        }
    public:
        /**
         * @param nums: A list of integers
         * @param k: As described
         * @return: The majority number
         */
        int majorityNumber(vector<int> nums, int k) 
        {
            int n = nums.size();
            
            auto mm = minmax_element(nums.begin(), nums.end());
            int minv = *mm.first, maxv = *mm.second;
    
            int dist = ((maxv - minv) / k) + 1;
    
            vector<pair<int, vector<int>>> bkt(k + 1, make_pair(0, vector<int>()));
            for(auto v: nums)
            {
                int inx = (v - minv) / dist;            
                bkt[inx].first ++;
                bkt[inx].second.push_back(v);
            }
    
            int tgt = n / k;
            for(auto &p : bkt)
            {
                if(p.first > tgt)
                {
                    auto rp = majorityNumber0(p.second);
                    if(rp.second > tgt)
                    {
                        return rp.first;
                    }
                }
            }
            return 0;
        }
    };

    And yes, the majorityNumber0() call can be inlined in the pass 1. That will make it O(k) space. One solution online with hashmap is very similar with the bucketing idea here.

  • 相关阅读:
    数据结构(2)
    python数据结构(1)
    python 中__getitem__ 和 __iter__ 的区别
    python 中的 %s,%r,__str__,__repr__
    python中的zip
    python反射,单例模式
    类python中高级用法
    python中super与成员属性
    python 类与对象解析
    【其他】BootCDN
  • 原文地址:https://www.cnblogs.com/tonix/p/4916201.html
Copyright © 2011-2022 走看看