Leetcode 164 array Maximum interval (linear complexity implementation)//python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.