【LeetCode】164. 最大间距 结题报告 (C++)

原题地址:https://leetcode-cn.com/problems/maximum-gap/description/

题目描述:

给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。

如果数组元素个数小于 2,则返回 0。

示例 1:

输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
示例 2:

输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
说明:

你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。

解题方案:

本题有些难,属于排序类型的题目,题目要求时间复杂度是线性的,就不能先对数组进行排序再进行查找最大差值。没有很好的思路,在网上查到了一个方法,采用的是桶排序。参考地址:https://blog.csdn.net/zxzxzx0119/article/details/82889998

桶排序第一次遇到,当然就不会做了,就当是学习啦。

代码:

class Solution {
public:
    int mapToBucket(long num, long len, long min, long max){
        return int((num - min) * len / (max - min));
    }

    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2)
            return 0;
        
        int len = nums.size();
        int a = nums[0], b = nums[0];
        for(int i = 0; i < len; i++){
            a = nums[i] < a ? nums[i] : a;
            b = nums[i] > b ? nums[i] : b;
        }
        if(a == b)
            return 0;
        
        //准备 n + 1个桶
        bool hasNum[len + 1] ;
        int mins[len + 1];
        int maxs[len + 1];

        for(int i = 0; i <= len; i++)
            hasNum[i] = false;
        for(int i = 0; i < len; i++){
            int bid = mapToBucket(nums[i], len, a, b);
            mins[bid] = hasNum[bid] ? min(mins[bid], nums[i]) : nums[i];
            maxs[bid] = hasNum[bid] ? max(maxs[bid], nums[i]) : nums[i];
            hasNum[bid] = true;
        }

        int res = 0, preMax = maxs[0]; //第一个桶一定不空  因为一定有一个 最小值

        // 每一个非空桶 都找到 左边离它最近的非空桶  然后计算答案
        for(int i = 1; i <= len; i++){
            if(hasNum[i]) { // 是非空的
                res = max(res, mins[i] - preMax);
                preMax = maxs[i];
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32805671/article/details/83064359