LeetCode 164. Maximum Gap

    xiaoxiao2021-03-26  22

    题目

    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.

    题解

    Suppose there are N elements and they range from A to B.

    Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

    Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

    for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

    Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

    For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

    题解是用了桶排序 max gap只可能出现在两个桶之间

    第一次意识到这个排序这么牛逼的应用

    吓得我去搜了一下桶排序

    桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序的一种归纳结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间(Θ(n))。但桶排序并不是比较排序,他不受到O(n log n)下限的影响。 桶排序以下列程序进行: 设置一个定量的数组当作空桶子。 寻访序列,并且把项目一个一个放到对应的桶子去。 对每个不是空的桶子进行排序。 从不是空的桶子里把项目再放回原来的序列中。 对于N个待排数据,M个桶,平均每个桶[N/M]个数据的桶排序平均时间复杂度为: O(N)+O(M*(N/M)*log(N/M))=O(N+N*(logN-logM))=O(N+N*logN-N*logM) 当N=M时,即极限情况下每个桶只有一个数据时。桶排序的最好效率能够达到O(N)。 总结:桶排序的平均时间复杂度为线性的O(N+C),其中C=N*(logN-logM)。如果相对于同样的N,桶数量M越大,其效率越高,最好的时间复杂度达到O(N)。当然桶排序的空间复杂度为O(N+M),如果输入数据非常庞大,而桶的数量也非常多,则空间代价无疑是昂贵的。此外,桶排序是稳定的。[1]

    代码

    class Solution { public: int maximumGap(vector<int>& nums) { if( nums.size() <= 1 ) return 0; int maxAll = *max_element( nums.begin(), nums.end() ); int minAll = *min_element( nums.begin(), nums.end() ); int n = nums.size(); double gap = (double)( maxAll - minAll ) / ( n - 1 ); vector<int> mi( n - 1, INT_MAX ); vector<int> ma( n - 1, INT_MIN ); for( int i = 0; i < n; i++ ){ if( nums[i] != maxAll ){ int index = (int)( nums[i] - minAll ) / gap; mi[index] = min( mi[index], nums[i] ); ma[index] = max( ma[index], nums[i] ); } } int ans = 0; int pre = ma[0]; for( int i = 1; i < n - 1; i++ ){ if( mi[i] != INT_MAX ){ ans = max( ans, mi[i] - pre ); pre = ma[i]; } } ans = max( ans, maxAll - pre ); return ans; } };
    转载请注明原文地址: https://ju.6miu.com/read-660364.html

    最新回复(0)