题目如下:
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.
分析如下:
考虑了很多方法,估计要用到bucket sort或者radix sort。后来放狗一搜发现果然要用到bucket sort.
基本思路是这样的,把n个数放到x个桶中。我们可以构造一个合适的x,并且通过下面的证明发现,max gap只可能出现在两个桶之间,不能出现在一个桶的内部。
下面是证明,直接抄官方的解答:
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 t