Leetcode 164 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

给定数组,找出数组排序后两个相邻数字的差的最大值是多少。

难点在于要求线性时间和空间复杂度完成。

不加这个要求,直接快排就可以了,加了这个要求怎么办呢?我也想了很久......

想了好久,看了题解,发现还是思维僵化,根本就没有想到桶排序

引用官方题解中的话

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

当所有元素均匀分布的时候,相邻数字的差的最大值最小,因此可以构造桶大小的为[(B - A) / (N - 1)],

同一个桶内的元素的差一定小于桶的大小,这样就不需要管桶内的大小关系了,只需要关注每个桶的最小值和前一个非空桶的最大值之差就可以了。

class Solution {
public:
    int maximumGap(vector& nums) {
        if(nums.size()<2) return 0;
        int minn = INT_MAX;
        int maxx = INT_MIN;
        for(int i = 0; i minb(cnt, INT_MAX);
        vector maxb(cnt, INT_MIN);
        for(int i = 0;i


你可能感兴趣的:(基础,leetcode)