线性排序算法 发表于 2018-08-30 | 阅读次数: 线性排序算法 复习一下线性排序算法:计数排序、桶排序与基数排序 三种线性排序算法 计数排序、桶排序与基数排序 线性排序算法(计数排序,基数排序,桶排序)分析及实现 Leetcode 164. Maximum Gap Leetcode 164. Maximum Gap 123456789101112131415161718192021222324252627282930313233343536373839//Radix Sortint 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;} 1234567891011121314151617181920212223242526272829303132333435363738//Buckets and The Pigeonhole Principleclass 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;}