164. Maximum Gap

来源:互联网 发布:爬虫软件官方下载 编辑:程序博客网 时间:2024/05/19 12:18

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(n)的时间复杂度和空间复杂度。不能简单的用sort排序然后计算,这样就不可能是O(n)。这里用桶排序。一开始我是直接用一个数一个桶(不在序列中的数也有桶)的方法,但[2,999999]这个例子超时了,因为差距有点大。为了缩小桶的数,要使用适当的桶大小,这里是序列有多少个数就有多少个桶,桶的大小即为均分Max-Min。每个桶都保存好在该桶中的最大值和最小值。这样最理想的情况是每个桶有一个数(这里指在序列中的数),这样两个数的距离就是一个桶的最小值和前一个桶的最大值的差,这样算最大值就可以。没那么理想的情况就是有些桶不只一个数,但这样肯定有某个桶缺了数,这个桶两边的相邻的数差比桶的大小还大,这样最大差肯定不在由两个或两个数以上的桶上产生。所以统一计算上一个有数的桶的最大值和下一个有数的桶的最小值,然后算最大值就能得到答案。


代码:

class Solution{public:int maximumGap(vector<int>& nums) {int Max = INT_MIN, Min = INT_MAX, len = nums.size();if(nums.size() < 2) return 0;for(auto num:nums){Max = max(Max, num);Min = min(Min, num);}int bucket_size = max(1, (Max - Min) / (len - 1));int bucket_num = (Max - Min) / bucket_size + 1;vector<int>bucket_cnt(bucket_num, 0);vector<int>bucket_max(bucket_num, INT_MIN);vector<int>bucket_min(bucket_num, INT_MAX);for(auto num:nums){int bucket_id = (num - Min) / bucket_size;++bucket_cnt[bucket_id];bucket_min[bucket_id] = min(bucket_min[bucket_id], num);bucket_max[bucket_id] = max(bucket_max[bucket_id], num);}int pre = Min, res = 0;for(int i = 0; i < bucket_num; ++i){if(bucket_cnt[i] > 0){res = max(res, bucket_min[i] - pre);pre = bucket_max[i];}}return res;}};


0 0
原创粉丝点击