164 Maximum Gap

164. Maximum Gap

1. Question

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.

2. Implementation

(1) Sort
1
class Solution {
2
public int maximumGap(int[] nums) {
3
if (nums == null || nums.length < 2) {
4
return 0;
5
}
6
7
Arrays.sort(nums);
8
int res = 0;
9
10
for (int i = 0; i < nums.length - 1; i++) {
11
res = Math.max(res, nums[i + 1] - nums[i]);
12
}
13
return res;
14
}
15
}
Copied!
(2) Bucket Sort
1
class Solution {
2
public int maximumGap(int[] nums) {
3
if (nums == null || nums.length < 2) {
4
return 0;
5
}
6
7
int n = nums.length;
8
int min = Integer.MAX_VALUE;
9
int max = Integer.MIN_VALUE;
10
11
for (int num : nums) {
12
min = Math.min(min, num);
13
max = Math.max(max, num);
14
}
15
16
if (min == max) {
17
return 0;
18
}
19
20
Bucket buckets[] = new Bucket[n];
21
22
for (int i = 0; i < n; i++) {
23
buckets[i] = new Bucket();
24
}
25
26
int bucketLen = (int)Math.ceil((double)(max - min) / (n - 1));
27
28
for (int num : nums) {
29
int index = (num - min)/bucketLen;
30
31
if (buckets[index].min == Integer.MAX_VALUE) {
32
buckets[index].min = num;
33
buckets[index].max = num;
34
}
35
else {
36
buckets[index].min = Math.min(buckets[index].min, num);
37
buckets[index].max = Math.max(buckets[index].max, num);
38
}
39
}
40
41
int maxGap = 0, prev = 0;
42
for (int i = 1; i < n; i++) {
43
if (buckets[i].min != Integer.MAX_VALUE) {
44
maxGap = Math.max(maxGap, buckets[i].min - buckets[prev].max);
45
prev = i;
46
}
47
}
48
return maxGap;
49
}
50
51
class Bucket {
52
int min, max;
53
54
public Bucket() {
55
min = Integer.MAX_VALUE;
56
max = Integer.MIN_VALUE;
57
}
58
}
59
}
Copied!

3. Time & Space Complexity

Sort: 时间复杂度O(nlogn), 空间复杂度O(1)
Bucket Sort: 时间复杂度O(n), 空间复杂度O(n)