letecode 编程学习(18)

题目

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

如果数组元素个数小于 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/qq_27124771/article/details/87651495
  • 取最大值maxVal和最小值minVal,那么桶之间的偏移间隔为d = max(1, (maxVal - minVal)/(n-1)), 桶的数量为 (maxVal - minVal)/d

代码

class Solution {
public:
    int maximumGap(vector<int>& nums) {

        if (nums.size() <2)
        {
            return 0;
        }

        int n = nums.size();
        int minVal = *min_element(nums.begin(), nums.end());

        int maxVal = *max_element(nums.begin(), nums.end());
        int d = max(1, (maxVal - minVal) / (n - 1));
        int bucketSize = (maxVal - minVal) / d + 1;

        std::vector<std::pair<int, int>> coutVec(bucketSize, make_pair(-1, -1));
        for (int i = 0; i < n; i++)
        {
            int index = int((nums[i] - minVal)/d);
            if ( coutVec[index].first == -1)
            {
                coutVec[index].first =  nums[i];
            }
            else
            {
                coutVec[index].first = coutVec[index].first > nums[i] ? nums[i] : coutVec[index].first;
            }
            
            if ( coutVec[index].second == -1)
            {
                coutVec[index].second =  nums[i];
            }
            else
            {
                coutVec[index].second = coutVec[index].second < nums[i] ? nums[i] : coutVec[index].second;
            }
        }

        int maxSum = 0;
        int pre = -1;

        for (int i = 0; i < bucketSize; i++ )
        {
            if (coutVec[i].first == -1)
            {
                continue;
            }

            if (pre != -1)
            {
                maxSum = max(maxSum, coutVec[i].first - coutVec[pre].second);
            }

            pre = i;
        }

        return maxSum;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值