基数排序示例/LeetCode 164. 最大间距

基数排序的思想是,对于一个给定的基数,每次排序构建基数数量的桶,并将数分配到桶里。

可以用count数组对桶中的数量计数,并转化为前缀数组记录桶中数字的位置。

LeetCode 164. 最大间距题解

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        long base=(1<<8);
        int cur_base=1;
        int n=nums.size();
        if(nums.size()<2) return 0;
        int max_num=*max_element(nums.begin(),nums.end());
        int count_time=0;
        while(max_num)
        {
            count_time++;
            max_num/=base;
        }
        for(int i=0;i<count_time;i++)
        {
            vector<int> count(base,0);
            for(auto num:nums)
            {
                int j=num/cur_base%base;
                count[j]++;
            }
            int cur_pos=0;
            for(int j=0;j<base;j++)
            {
                int tmp=count[j];
                count[j]=cur_pos;
                cur_pos+=tmp;
            }
            vector<int> nums_tmp(n);
            for(auto num:nums)
            {
                nums_tmp[count[num/cur_base%base]++]=num;

            }
            nums=nums_tmp;
            cur_base*=base;

        }
        int res=0;
        for(int i=0;i<n-1;i++)
        {
            res=max(res,nums[i+1]-nums[i]);
        }
        return res;
    }
};
View Code

 

posted @ 2022-04-15 10:19  80k  阅读(40)  评论(0)    收藏  举报