Leetcode Address: https://leetcode.com/problems/maximum-gap/description/
Title Description
Given an unordered array, find the maximum interval between the sorted elements.
It is required to be implemented with linear time complexity.
For example: The input is "3,6,9,1,10" and the output should be the maximum interval of 3.
Problem analysis
Linear time complexity implementation, it means that the element cannot be sorted first, because the complexity of this method is O(n? Log(n))
The idea is to use the bucket sorting method.
First, the largest element in the random array, the smallest element, is the linear time complexity;
Then, between the maximum element and the smallest element, an interval of (N-1) is allocated, which is N buckets (buckets). Each bucket is an ordered real pair (None,none), and each number is then plugged into the target bucket in turn.
where the upper and lower bounds of the bucket have elements (there is a bucket corresponding to multiple elements), then only the new element and the lower bound of the smaller values, and calculate its upper bound with a larger value, and the maximum value as a new nether/upper bound;
Finally, the difference between the lower bound of each bucket and the upper section of the next bucket is calculated. The maximum value for the difference is the maximum interval.
Time complexity of o(n+b)≈o(n)
Full Code (Python)
defmaximumgap (num):ifLen (num) < 2orMIN (num) = =max (num):return0 A, b=min (num), max (num) size= (b-a)//(LEN (num)-1)or1Buckets= [None, none] for_inchRange ((b-a)//size+1)] forNinchnum:b= bucket[(n-a)//size] b[0]= NifB[0] isNoneElsemin (b[0], n) b[1] = nifB[1] isNoneElseMax (b[1], N) Buckets= [b forBinchBucketsifB[0] is notNone]returnMax (Bucket[i][0]-bucket[i-1][1] forIinchRange (1, len (bucket)))
Leetcode 164 Array maximum interval (linear complexity implementation)//python