码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Maximum Gap

时间:2015-01-01 00:07:06      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

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

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;
    }
};

  

[leetcode]Maximum Gap

标签:

原文地址:http://www.cnblogs.com/lautsie/p/4196780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!