【LeetCode】164. Maximum Gap (2 solutions)


Maximum Gap

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

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

 

解法一:

先排序O(nlogn),再一次遍歷,得到maxGap

雖然不滿足O(n)的時間要求,但是最直觀的想法。

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

 

解法二:為了滿足O(n)復雜度,我嘗試了計數排序,但是會TLE。因此使用桶排序來做。

(計數排序可以看做是桶大小為1的桶排序,但由於桶數目太多導致遍歷時間過長。)

最大gap肯定是出現在后一個有效桶的min與前一個有效桶的max之間。

“有效”指的是忽略空桶。

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.empty() || nums.size() == 1)
            return 0;
        int n = nums.size();
        int minAll = *min_element(nums.begin(), nums.end());
        int maxAll = *max_element(nums.begin(), nums.end());
        // type conversion!!!
        double gap = ((double)(maxAll - minAll)) / (n - 1);
        // compute min and max element for each bucket
        vector<int> minV(n-1, INT_MAX);
        vector<int> maxV(n-1, INT_MIN);
        for(int i = 0; i < n; i ++)
        {
            if(nums[i] != maxAll)
            {// the bktId of maxAll will fall out of bucket range
                int bktId = (int)((nums[i]-minAll)/gap);
                minV[bktId] = min(minV[bktId], nums[i]);
                maxV[bktId] = max(maxV[bktId], nums[i]);
            }
        }
        int ret = 0;
        int curMax = maxV[0];
        for(int i = 1; i < n-1; i ++)
        {
            if(minV[i] != INT_MAX)
            {
                ret = max(ret, minV[i]-curMax);
                curMax = maxV[i];
            }
        }
        ret = max(ret, maxAll-curMax);
        return ret;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM