线性排序算法

线性排序算法

复习一下线性排序算法:计数排序、桶排序与基数排序

Leetcode 164. 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
//Radix Sort
int maximumGap(vector<int>& nums)
{
if (nums.empty() || nums.size() < 2)
return 0;
int maxVal = *max_element(nums.begin(), nums.end());
int exp = 1; // 1, 10, 100, 1000 ...
int radix = 10; // base 10 system
vector<int> aux(nums.size());
/* LSD Radix Sort */
while (maxVal / exp > 0) { // Go through all digits from LSD to MSD
vector<int> count(radix, 0);
for (int i = 0; i < nums.size(); i++) // Counting sort
count[(nums[i] / exp) % 10]++;
for (int i = 1; i < count.size(); i++) // you could also use partial_sum()
count[i] += count[i - 1];
for (int i = nums.size() - 1; i >= 0; i--)
aux[--count[(nums[i] / exp) % 10]] = nums[i];
for (int i = 0; i < nums.size(); i++)
nums[i] = aux[i];
exp *= 10;
}
int maxGap = 0;
for (int i = 0; i < nums.size() - 1; i++)
maxGap = max(nums[i + 1] - nums[i], maxGap);
return maxGap;
}
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
//Buckets and The Pigeonhole Principle
class Bucket {
public:
bool used = false;
int minval = numeric_limits<int>::max(); // same as INT_MAX
int maxval = numeric_limits<int>::min(); // same as INT_MIN
};
int maximumGap(vector<int>& nums)
{
if (nums.empty() || nums.size() < 2)
return 0;
int mini = *min_element(nums.begin(), nums.end()),
maxi = *max_element(nums.begin(), nums.end());
int bucketSize = max(1, (maxi - mini) / ((int)nums.size() - 1)); // bucket size or capacity
int bucketNum = (maxi - mini) / bucketSize + 1; // number of buckets
vector<Bucket> buckets(bucketNum);
for (auto&& num : nums) {
int bucketIdx = (num - mini) / bucketSize; // locating correct bucket
buckets[bucketIdx].used = true;
buckets[bucketIdx].minval = min(num, buckets[bucketIdx].minval);
buckets[bucketIdx].maxval = max(num, buckets[bucketIdx].maxval);
}
int prevBucketMax = mini, maxGap = 0;
for (auto&& bucket : buckets) {
if (!bucket.used)
continue;
maxGap = max(maxGap, bucket.minval - prevBucketMax);
prevBucketMax = bucket.maxval;
}
return maxGap;
}