164. Maximum Gap
by Botao Xiao
Questions:
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.
Thinking:
- Method 1:
- 先排序,再从头开始遍历找出max gap。
- 并不满足题目要求的O(N),这种方法的复杂度是O(N + NlgN).
-
class Solution { public int maximumGap(int[] nums) { Arrays.sort(nums); int diff = 0; for(int i = 1; i < nums.length; i++) diff = Math.max(diff, nums[i] - nums[i - 1]); return diff; } }
二刷
- 研究了桶排序的原理。
class Solution {
public int maximumGap(int[] nums) {
if(nums.length <= 1) return 0;
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for(int num : nums){
max = Math.max(max, num);
min = Math.min(min, num);
}
if(max == min) return 0;
if(nums.length == 2) return max - min;
int len = (int)Math.ceil((double)(max - min) / (nums.length - 1));
int n = (max - min) / len;
int[] minValues = new int[n + 1];
int[] maxValues = new int[n + 1];
for(int i = 0; i < n + 1; i++){
minValues[i] = Integer.MAX_VALUE;
maxValues[i] = Integer.MIN_VALUE;
}
for(int num : nums){
int index = (num - min) / len;
minValues[index] = Math.min(minValues[index], num);
maxValues[index] = Math.max(maxValues[index], num);
}
int result = 0;
int pre = -1;
for(int i = 0; i < n + 1; i++){
if(minValues[i] != Integer.MAX_VALUE){
if(pre != -1)
result = Math.max(result, minValues[i] - pre);
pre = maxValues[i];
}
}
return result;
}
}
Subscribe via RSS