[LeetCode] 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.

class Solution {
public:
    int maximumGap(vector<int> &num) {
        if(num.size() < 2) return 0;
        int maxNum = num[0],minNum = num[0];
        for(int i : num){
            maxNum = max(i,maxNum);
            minNum = min(i,minNum);
        }
        int gap = ceil((maxNum - minNum) * 1.0 / (num.size() - 1));
        vector<vector<int> > buckets((maxNum - minNum) / gap + 1);
        for(int x : num){
            int i = (x - minNum) / gap;
            if(buckets[i].empty()){
                buckets[i].push_back(x);
                buckets[i].push_back(x);
            }else{
                if(x < buckets[i][0]) buckets[i][0] = x;
                if(x > buckets[i][1]) buckets[i][1] = x;
            }
        }
        int ans = 0,pre = 0;
        for(int i = 1;i < buckets.size();i ++){
            if(buckets[i].empty()) continue;
            ans = max(ans,buckets[i][0] - buckets[pre][1]);
            pre = i;
        }
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章