164. Maximum Gap

问题描述:

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Return 0 if the array contains less than 2 elements.

Example 1:

Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
             (3,6) or (6,9) has the maximum difference 3.

Example 2:

Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

Note:

  • You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
  • Try to solve it in linear time/space.

 

解题思路:

一开始首先想到先排序挨个算一遍,这样的话时间复杂度为O(nlogn + n)

但是后来看到说尝试在线性时间和空间中去解

没有什么好想法的我看了Grandyang的总结

使用了桶排序。

关于桶排序:https://blog.csdn.net/mupengfei6688/article/details/53106267

注意的是先找桶的大小,再找桶的个数。

最大差出现在桶与桶之间

 

 

代码:

O(nlogn)

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2)
            return 0;
        sort(nums.begin(), nums.end());
        int ret = 0;
        for(int i = 0; i < nums.size() - 1; i++){
            ret = max(ret, nums[i+1] - nums[i]);
        }
        return ret;
    }
};

 

 

O(n)

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2) return 0;
        int mx = INT_MIN, mn = INT_MAX, n = nums.size();
        for(int i : nums){
            mx = max(mx, i);
            mn = min(mn, i);
        }
        int size = (mx - mn) / n + 1;
        int bucket_nums = (mx - mn) /size + 1;
        vector<int> bucket_min(bucket_nums, INT_MAX);
        vector<int> bucket_max(bucket_nums, INT_MIN);
        set<int> s;
        for(int d : nums) {
            int idx = (d - mn) / size;
            bucket_min[idx] = min(bucket_min[idx], d);
            bucket_max[idx] = max(bucket_max[idx], d);
            s.insert(idx);
        }
        int pre = 0, res = 0;
        for (int i = 1; i < n; ++i) {
            if (!s.count(i)) continue;
            res = max(res, bucket_min[i] - bucket_max[pre]);
            pre = i;
        }
        return res;
    }
};

 

posted @ 2018-06-27 06:47  妖域大都督  阅读(103)  评论(0编辑  收藏  举报