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>& nums) {
        int n = nums.size();
	    if (n < 2)
	    {
		    return 0;
	    }

	    int maxVal = nums[0];
	    int minVal = nums[0];

	    for (int i = 1; i < n; i++)
	    {
		    if (nums[i] > maxVal)
		    {
			    maxVal = nums[i];
		    }
		    else if (nums[i] < minVal)
		    {
			    minVal = nums[i];
		    }
	    }

	    int bucketSize = max(1, (maxVal-minVal)/(n-1));//桶排序
	    int bucketNum = (maxVal-minVal)/bucketSize + 1;
	    int counter[bucketNum];
	    int maxElement[bucketNum];
	    int minElement[bucketNum];
	    for (int i = 0; i < bucketNum; i++)
	    {
		    counter[i] = 0;
		    maxElement[i] = minVal;
		    minElement[i] = maxVal;
	    }
	
	    for (int i = 0; i < n; i++)
	    {
		    int id = (nums[i]-minVal)/bucketSize;
		    counter[id]++;
		    if (nums[i] > maxElement[id])
		    {
			    maxElement[id] = nums[i];
		    }
		    if (nums[i] < minElement[id])
		    {
			    minElement[id] = nums[i];
		    }
	    }
	
	    int prevMax = minVal;
	    int result = 0;
	    for (int i = 0; i < bucketNum; i++)
	    {
		    if (counter[i] > 0)
		    {
			    int temp = minElement[i] - prevMax;
			    if (temp > result)
			    {
				    result = temp; 
			    }
			    prevMax = maxElement[i];
		    }
	    }

	    return result;
    }
};


你可能感兴趣的:(Maximum Gap)