• [leetcode]Maximum Gap


    用分桶的做法,思路参考自网友,很精妙。

    class Solution {
    public:
        int maximumGap(vector<int> &num) {
            int size = num.size();
            if (size < 2) {
                return 0;
            }
            int maxVal = *max_element(num.begin(), num.end());
            int minVal = *min_element(num.begin(), num.end());
            int gap = (maxVal - minVal - 1) / (size - 1) + 1; // ceiling function
            int bucketSize = (maxVal - minVal) / gap;
            vector<int> minBucket(bucketSize, INT_MAX);
            vector<int> maxBucket(bucketSize, INT_MIN);
            for (int i = 0; i < size; i++) {
                if (num[i] == minVal || num[i] == maxVal) {
                    continue;
                }
                int idx = (num[i] - minVal) / gap;
                minBucket[idx] = min(minBucket[idx], num[i]);
                maxBucket[idx] = max(maxBucket[idx], num[i]);
            }
            int maxGap = INT_MIN;
            int prev = minVal;
            for (int i = 0; i < bucketSize; i++) {
                if (minBucket[i] != INT_MAX) {
                    maxGap = max(maxGap, minBucket[i] - prev);
                    prev = maxBucket[i];
                }
            }
            maxGap = max(maxGap, maxVal - prev);
            return maxGap;
        }
    };
    

      

  • 相关阅读:
    POJ 3093 Margaritas on the River Walk(背包)
    BZOJ 2287 【POJ Challenge】消失之物(DP+容斥)
    WC2017 Day1
    WC2017 Day0
    WC2017 Conclusion
    WC2017 Day6
    UOJ #58 糖果公园
    WC2017 Day5
    codevs 1946 阿狸的打字机
    HDU 2457 DNA_repair
  • 原文地址:https://www.cnblogs.com/lautsie/p/4196780.html
Copyright © 2020-2023  润新知