leetcode 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.
题目来源:https://leetcode.com/problems/maximum-gap/

分析

一个没有排序的数组,返回排好序后的相邻之间元素的最大间隔。
苦思冥想想不出来,参考了一下网上的的做法(参考链接),自己慢慢消化吧。使用若干个桶存放所有元素,使得最大的gap位于两个桶之间(前面桶的最小值和随后桶的最大值之差)。这样的话,桶的数目该是多少位宜呢?平均分割元素区间(max_elm - min_elm),每个区间的大小是一个avg_gap。这样的话,如果所有元素平均分布,则每个桶里一个元素,退化为排序。如果不平均分布,则必然有的桶为空,有的桶里面的元素多于1个。最大的gap也就不可能出现在一个桶里面,求不同桶之间的gap就行了。

这里写图片描述

代码

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int len = nums.size();
        if(len < 2)
            return 0;
        //find max element
        int max_num = *max_element(nums.begin(), nums.end());
        //find min element
        int min_num = *min_element(nums.begin(), nums.end());
        //average gap, ceil(0.3) = 1
        int avg_gap = ceil((double)(max_num - min_num)/(len - 1));
        int bucket_num = ceil((double)(max_num - min_num) / avg_gap);
        //buckets.first is max element in this bucket, initialized by the min integer(0x80000000)
        //buckets.second is min element in this bucket, initialized by the max integer(0x7fffffff)
        vector<pair<int, int> >buckets(bucket_num, make_pair(0x80000000, 0x7fffffff));
        for(auto val : nums){
            if(val == max_num || val == min_num)
                continue;
            int i = (val - min_num) / avg_gap;//find the correct bucket
            if(val > buckets[i].first)
                buckets[i].first = val;
            if(val < buckets[i].second)
                buckets[i].second = val;
        }
        int max_gap = 0;
        int last_max = min_num;
        for(auto bucket : buckets){
            if(bucket.first == 0x80000000)//empty bucket
                continue;
            int cur_max = bucket.first;
            int cur_min = bucket.second;
            max_gap = max(max_gap, cur_min - last_max);
            last_max = cur_max;
        }
        max_gap = max(max_gap, max_num - last_max);
        return max_gap;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值