基数排序板子

复杂度O(N)的非负整数排序

class Solution {
public:
    void radixSort(vector<int>& nums) {
        int n = nums.size();
        int exp = 1;
        vector<int> buf(n);
        int mx = *max_element(nums.begin(), nums.end());
        while(exp <= mx) {
            vector<int> cnt(10); //十进制10位
            for(int i = 0; i < n; i++) { 
                int d = (nums[i] / exp) % 10; //exp位的数字
                cnt[d]++;
            }
            for(int i = 1; i < 10; i++) {
                cnt[i] += cnt[i - 1];
            }
            for(int i = n - 1; i >= 0; i--) {
                int d = (nums[i] / exp) % 10;
                buf[cnt[d] - 1] = nums[i];
                cnt[d]--;
            }
            copy(buf.begin(), buf.end(), nums.begin());
            exp *= 10;
        }
        return;
    }
};
posted @ 2021-01-11 22:17  wrjlinkkkkkk  阅读(48)  评论(0编辑  收藏  举报