首页 > 其他 > 详细

LintCode "Majority Number III"

时间:2015-10-28 07:00:40      阅读:297      评论:0      收藏:0      [点我收藏+]

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.

LintCode "Majority Number III"

原文:http://www.cnblogs.com/tonix/p/4916201.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!