LeetCode164 Maximum Gap

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

Return 0 if the array contains less than 2 elements.

Example 1:

Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
             (3,6) or (6,9) has the maximum difference 3.

Example 2:

Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

Note:

  • You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
  • Try to solve it in linear time/space.

题源:here;完整实现:here

思路:

1 暴力求解:将原数据排序然后求最大间隔;2 利用“桶”的概念实现常数时间复杂度。

解法一

class Solution {
public:
	int maximumGap(vector<int>& nums) {
		if (nums.size() < 2) return 0;
		vector<int> tmp = nums;
		sort(tmp.begin(), tmp.end());
		int res = INT_MIN;
		for (decltype(nums.size()) i = 1; i < nums.size(); i++) {
			res = max(res, abs(tmp[i] - tmp[i-1]));
		}
		return res;
	}

};

解法二

class Bucket {
public:
	bool used = false;
	int _min = INT_MAX;
	int _max = INT_MIN;
};

class Solution2 {
public:
	int maximumGap(vector<int> &nums) {
		if (nums.size() < 2) return 0;
		int mini = *min_element(nums.begin(), nums.end());
		int maxi = *max_element(nums.begin(), nums.end());
		int bSize = max(1, (maxi - mini) / int(nums.size() - 1));
		int bNum = (maxi - mini) / bSize + 1;
		vector<Bucket> buckets(bNum);
		for (auto num : nums) {
			int bIdx = (num - mini) / bSize;
			buckets[bIdx].used = true;
			buckets[bIdx]._min = min(num, buckets[bIdx]._min);
			buckets[bIdx]._max = max(num, buckets[bIdx]._max);
		}

		int preMax = mini, res = INT_MIN;
		for (auto bucket : buckets) {
			if (!bucket.used) continue;
			res = max(res, bucket._min - preMax);
			preMax = bucket._max;
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88187540
GAP
GAP
今日推荐