leetcode Maximum Gap

来源:互联网 发布:最新在线报名系统源码 编辑:程序博客网 时间:2024/06/08 19:56

题目

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