-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Gap
40 lines (38 loc) · 1.19 KB
/
Maximum Gap
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
35
36
37
38
39
40
class Solution {
public:
int maximumGap(vector<int> &num) {
if (num.size() <= 1) return 0;
int res = -1;
radixSort(num);
for(int i = 1; i < num.size(); ++i) {
res = max(res, num[i] - num[i-1]);
}
return res;
}
void radixSort(vector<int> &num) {
int maxN = -1;
for(auto i : num) {
maxN = max(maxN, i);
}
//create 10 buckets, each for a digit
int base = 10;
vector< vector<int> > bucket (base);
vector<int> tmpVec = num; //keep partially sorted list after each iteration
for (long long i = 1; i <= maxN; i *= 10) {
for(int j = 0; j < tmpVec.size(); ++j) {
int digit = (tmpVec[j] / i) % base;
bucket[digit].push_back(tmpVec[j]);
}
//update temp vector
int m = 0; //index of tmpVec
for (int j = 0; j < base; ++j) {
for (size_t k = 0; k < bucket[j].size(); ++k) {
tmpVec[m] = bucket[j][k];
m++;
}
bucket[j].clear();
}
}
num = tmpVec;
}
};