You have reached the world's edge, none but devils play past here
0%
基数排序+计数排序+桶排序
Posted onEdited on Symbols count in article: 4.5kReading time ≈4 mins.
基数排序+计数排序+桶排序梳理
计数排序
计数排序(Counting sort)是一种稳定的线性时间排序算法。该算法于1954年由 Harold H. Seward 提出。计数排序使用一个额外的数组{\displaystyle C} C ,其中第i个元素是待排序数组{\displaystyle A}A中值等于{\displaystyle i}i的元素的个数。然后根据数组{\displaystyle C} C 来将{\displaystyle A}A中的元素排到正确的位置。
// 基数排序 classSolution { public: // 'nums' must consist of values from 0 to 1000000000 only intmaximumGap(vector<int>& nums){ int n = nums.size(); if (n < 2) return0;
vector<int> oVec(n); int max_num = *max_element(nums.cbegin(), nums.cend());
for (int i = 1; i <= max_num; i *= 10) { array<int, 10> count{}; for (int j = 0; j < n; ++j) { int idx = nums[j] / i % 10; count[idx]++; }
for (int k = 1; k < 10; ++k) count[k] += count[k-1];
// 反向很重要,保持稳定性,这样排百位的时候个位也是有序的 for (int j = n - 1; j >= 0; --j) { int idx = nums[j] / i % 10; oVec[count[idx] - 1] = nums[j]; count[idx]--; }
nums.swap(oVec); }
int ans = 0; for (int i = 1; i < n; ++i) ans = max(nums[i] - nums[i-1], ans);
// 桶排序 classSolution { public: intmaximumGap(vector<int>& nums){ int n = nums.size(); if (n < 2) return0;
int max_num = *max_element(nums.begin(), nums.end()); int min_num = *min_element(nums.begin(), nums.end()); int bl = max(1, (max_num - min_num) / (n - 1)); int bc = (max_num - min_num) / bl + 1; // 本题的数的取值范围是 // nums' must consist of values from 0 to 1000000000 only vector<pair<int, int>> bucket(bc, {INT_MAX, INT_MIN}); int ans = 0; for (constauto& num : nums) { int idx = (num - min_num) / bl; bucket[idx].first = min(bucket[idx].first, num); bucket[idx].second = max(bucket[idx].second, num); }
int prev_second = INT_MIN; for (int i = 0; i < bc; ++i) { if (prev_second != INT_MIN && bucket[i].first != INT_MAX) ans = max(ans, bucket[i].first - prev_second);
if (bucket[i].second != INT_MIN) prev_second = bucket[i].second; }