[LeetCode] Maximum Gap

164. Maximum Gap

Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.

You must write an algorithm that runs in linear time and uses linear extra space.

  • bucket sort solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int maximumGap(vector<int>& nums) {
int mi = *min_element(begin(nums), end(nums)), ma = *max_element(begin(nums), end(nums));
if(mi == ma) return 0;
int n = nums.size();
int gap = (ma - mi) / n + 1;
vector<int> miB(n, INT_MAX), maB(n, INT_MIN);

for(auto n : nums) {
int bucket = (n - mi) / gap;
miB[bucket] = min(n, miB[bucket]);
maB[bucket] = max(n, maB[bucket]);
}

int prv = maB[0], res = gap;
for(int i = 1; i < n; i++) {
if(miB[i] == INT_MAX) continue;
res = max(res, miB[i] - prv);

prv = maB[i];
}

return res;
}
};
  • radix sort solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
queue<int> q[10];
void radixSort(vector<int>& nums, int p) {
int d = pow(10,p);

for(int& n : nums) {
int bucket = (n / d) % 10;
q[bucket].push(n);
}

int index = 0;

for(int i = 0; i <= 9; i++) {
while(!q[i].empty()) {
nums[index++] = q[i].front(); q[i].pop();
}
}
}
public:
int maximumGap(vector<int>& nums) {
int d = log10(*max_element(begin(nums),end(nums)));

for(int i = 0; i <= d; i++)
radixSort(nums,i);

int res = 0;

for(int i = 0; i < nums.size() - 1; i++) {
res = max(res, nums[i+1] - nums[i]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/LeetCode/maximum-gap/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.