LeetCode 164 - Maximum Gap (Hard)
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.
方法1: 按照题意直接做即可。
思路:先排序。然后比较得出最大的max gap
time complexity: O(nlogn) space complexity O(1)
class Solution: def maximumGap(self, nums: List[int]) -> int: if not nums or len(nums) < 2: return 0 nums.sort() res = 0 for i in range(1, len(nums)): res = max(res, nums[i] - nums[i-1]) return res
方法2: bucket sort
思路:
1 找到整个list的最大值max 和最小值min
2 得到bucket size => (max-min)//(n - 1) (不减1也可以)
3 得到buckNum => (max - min ) // bucket size + 1 (at least需要一个桶,所以一定要+1)
4 把每个list中的数字放到相应的bucket中。筛掉没有使用过的桶。最后在有效的桶中,遍历一遍即可。
time complexity:O(n) space complexity: O(b) b is the number of buckets
class Solution: def maximumGap(self, nums: List[int]) -> int: if not nums or len(nums) < 2: return 0 minNum = min(nums) maxNum = max(nums) n = len(nums) buckSize = max(1, (maxNum - minNum) // (n - 1)) buckNum = (maxNum - minNum) // buckSize + 1 buckets = [[None, None] for _ in range(buckNum)] for num in nums: index = (num - minNum) // buckSize buckets[index][0] = num if buckets[index][0] is None else min(num, buckets[index][0]) buckets[index][1] = num if buckets[index][1] is None else max(num, buckets[index][1]) validBucket = [b for b in buckets if b[0] is not None] res = 0 for i in range(1, len(validBucket)): res = max(res, validBucket[i][0] - validBucket[i-1][1]) return res
浙公网安备 33010602011771号