Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

posted on 2015-10-28 06:10  Tonix  阅读(197)  评论(0编辑  收藏  举报