• LintCode "Maximum Gap"


    Bucketing! A lot of details to take care.

    struct Bucket
    {
        Bucket() :l(-1), r(-1), bValid(false){};
    int l, r;
        bool bValid;
    };
    
    class Solution {
    public:
        /**
        * @param nums: a vector of integers
        * @return: the maximum difference
        */
        int maximumGap(vector<int> nums)
        {
            //  Remove duplicates
            unordered_set<int> hs(nums.begin(), nums.end());
            nums.assign(hs.begin(), hs.end());
            //
            size_t n = nums.size();
            if (n < 2) return 0;
            
            long long mn = *min_element(nums.begin(), nums.end());
            long long mx = *max_element(nums.begin(), nums.end());
            if (mn == mx) return 0;
    
            //  Set up buckets
            vector<Bucket> bk(n);
            long long interval = (mx - mn + 1) / (long long)(n - 1);
    for (auto v : nums)
            {
                int binx = (v - mn) / interval;
                bk[binx].l = (!bk[binx].bValid) ? v : min(bk[binx].l, v);
                bk[binx].r = (!bk[binx].bValid) ? v : max(bk[binx].r, v);
                bk[binx].bValid = true;
            }
    
            //  Go check bucket by bucket
            int i = 0, ret = 0;
            while (i < bk.size())
            {
                if (bk[i].bValid)
                {
                    int wi = bk[i].r - bk[i].l, wo = 0;
                    
                    int j = i + 1;
                    while (j < bk.size() && !bk[j].bValid) j++;
                    if (j < bk.size())
                        wo = bk[j].l - bk[i].r;
                    
                    ret = max(ret, max(wi, wo));
                    i = j;
                }
                else
                    i++;
            }
            return ret;
        }
    };
  • 相关阅读:
    ios 学习小笔记
    object c 2.0 @property属性
    uiPickerView 滚动盘
    ios 文件操作
    ios多窗体项目
    Linux命令
    Mina的使用
    设计模式学习总结访问者模式(Visitor Method)
    socket, nio socket 及nio socket框架MINA总结
    UML类图与类的关系详解UML一波流系列(转转)
  • 原文地址:https://www.cnblogs.com/tonix/p/4858616.html
Copyright © 2020-2023  润新知