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.

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

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss

题目大意:

给定一个未排序的数组,找出其排序后的序列中两个相邻元素之间的最大差值。

最好在线性时间、线性空间复杂度内完成。

如果数组少于2个元素,返回0

可以假设数组中的所有元素均为非负整数,并且在32位带符号整数的范围以内。

解题思路:

基数排序(radix sort)/桶排序(bucket sort)

官方版(桶排序):

假设有N个元素A到B。

那么最大差值不会大于ceiling[(B - A) / (N - 1)]

令bucket(桶)的大小len = ceiling[(B - A) / (N - 1)],则最多会有(B - A) / len + 1个桶

对于数组中的任意整数K,很容易通过算式loc = (K - A) / len找出其桶的位置,然后维护每一个桶的最大值和最小值

由于同一个桶内的元素之间的差值至多为len - 1,因此最终答案不会从同一个桶中选择。

对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。


class Solution {
	public:
		int maximumGap(vector<int> &num) { 
			if (num.empty() || num.size() < 2)
				return 0;
			int Max = *max_element(num.begin(), num.end());
			int Min = *min_element(num.begin(), num.end());

			int gap = (int)ceil((double)(Max-Min)/(num.size() - 1));
			int bucketNum = (int) ceil((double)(Max-Min)/gap);
			vector<int> bucketsMin(bucketNum, INT_MAX);	
			vector<int> bucketsMax(bucketNum, INT_MIN);

			for (int i = 0; i < num.size(); i++) {
				if (num[i] == Max || num[i] == Min)
					continue;
				int idx = (num[i] - Min) / gap;
				bucketsMin[idx] = min(bucketsMin[idx], num[i]);
				bucketsMax[idx] = max(bucketsMax[idx], num[i]);
			}

			int ans = INT_MIN;
			int previous = Min;
			for (int i = 0; i < bucketNum; i++) {
				if (bucketsMin[i] == INT_MAX || bucketsMax[i] == INT_MIN) 
					continue;
				ans = max(ans, bucketsMin[i] - previous);
				previous = bucketsMax[i];
			}

			ans = max(ans, Max - previous);
			return ans;
		}
};


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