164. Maximum Gap (Array; sort)

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.

思路:题目的意思是在排序的情况下,相邻元素差值的最大值。由于限制O(n)时间复杂度,所以不能用快排等排序方法,使用桶排序(bucket sort)

 

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int size = nums.size();
        if(size < 2) return 0;
        if(size == 2) return abs(nums[0]-nums[1]);
        
        int maxValue=INT_MIN, minValue = INT_MAX;
        for(int i = 0; i < size; i++){
            if(nums[i]>maxValue) maxValue = nums[i];
            if(nums[i]<minValue) minValue = nums[i];
        }
        
        //determine the number of buckets (on average, one element in on bucket)
        int avgGap = ceil((double)(maxValue - minValue) / (size-1)); // 平均间隔
        if(avgGap == 0) return 0;
        int bucketNum = ceil((double)(maxValue - minValue) / avgGap);
        int bucketIndex;
        vector<pair<int, int>> buckets(bucketNum, make_pair(INT_MIN, INT_MAX)); // 初始化桶, save max and min of each bucket
       
        for(int i = 0; i < size; i++){
            //the last element(maxValue) should be dealt specially, for example [100,1,2,3],otherwise its index will be out of bound.
            if(nums[i] == maxValue) continue; 
            
            //determine the bucket index
            bucketIndex = (nums[i]-minValue) / avgGap; 
            if(nums[i]>buckets[bucketIndex].first) buckets[bucketIndex].first = nums[i]; //update max of the bucket
            if(nums[i]<buckets[bucketIndex].second) buckets[bucketIndex].second = nums[i]; //update min of the bucket
        }
        
        //max difference must exists between buckets if there're more than one bucket(because in buckets, gap at maximum = avgGap)
        int preIndex = 0;
        int maxGap = buckets[preIndex].first - minValue;;
        int gap;
        
        for(int i = preIndex+1; i < bucketNum; i++){
            if(buckets[i].first == INT_MIN) continue; //ignore empty 
            gap = buckets[i].second-buckets[preIndex].first;
            if(gap > maxGap) {
                maxGap = gap;
            }
            preIndex = i;
        }
        gap = maxValue - buckets[preIndex].first;
        if(gap > maxGap) {
            maxGap = gap;
        }
        return maxGap;
    }
};

 

posted on 2017-03-20 23:55  joannae  阅读(89)  评论(0编辑  收藏  举报

导航