[leetcode] 164. Maximum Gap 解题报告

本文介绍了一种使用基数排序解决LeetCode上最大间隔问题的方法。该问题要求找到数组排序后相邻元素的最大差距,且需在线性时间和空间复杂度内完成。文章详细解释了基数排序的原理,并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/maximum-gap/

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.


思路:一开始就想到基数排序时间和空间复杂度都是线性,不过只有在数字比较集中的时候速度才比较快,也就是其时间复杂度是O(k*n),其中k是最大数字有几位,n是数组长度.所以就想应该不会用这种方法吧,应该还有其他方法,没想到真的是这种算法.坑爹啊!

基数排序不是基于比较的排序算法,是基于RAM的,也就是基于内存的排序.其原理是从低位到高位统计在那一位0-9出现的次数,然后将数组按照那一位的大小排序.

代码如下:

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2) return 0;
        int len =to_string(*max_element(nums.begin(), nums.end())).size(); 
        int radix=1, maxGap=0, n=nums.size();
        for(int i = 0; i< len; i++)
        {
            vector<int> count(10, 0), vec(n);
            for(int val: nums) count[(val/radix)%10]++;
            for(int j=1; j<10; j++) count[j]+= count[j-1];
            for(int j=n-1; j >=0; j--) 
                vec[--count[(nums[j]/radix)%10]] = nums[j];
            for(int j =0; j< n; j++) nums[j] = vec[j];
            radix *= 10;
        }
        for(int i =1; i< n; i++) maxGap=max(maxGap, nums[i]-nums[i-1]);
        return maxGap;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值