Java for Leetcode 163 Maximum Gap

Source: Internet
Author: User

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.

Assume all elements in the array is non-negative integers and fit in the 32-bit signed integer range.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

Problem Solving Ideas:

Due to the use of linear time complexity, the comparison of the sorting has not been applied ("Introduction to the Algorithm" P108), can be used to count sorting, base sorting, heap sorting, because the counting sort is more suitable for a small range, the cardinal sort will eventually be sorted out, and we do not need to be so complex, so can be sorted by buckets, Select the appropriate distance between the buckets to ensure the maximum successive distance between the two barrels, Java implementation is as follows:

    public int maximumgap (int[] nums) {if (nums.length <= 1) return 0;int min = nums[0], max = nums[0];for (int num:nums) {min = math.min (min, num); max = Math.max (max, num);}  if (max = = min) return 0;int distance = Math.max (1, (max-min)/(nums.length-1)); int bucket[][] = new int[(max-min)/ Distance + 1][2];for (int i = 0; i < bucket.length; i++) {bucket[i][0] = integer.max_value;bucket[i][1] =-1;} for (int num:nums) {int i = (num-min)/distance;bucket[i][0] = math.min (num, bucket[i][0]); bucket[i][1] = Math.max (nu M, bucket[i][1]);} int maxdistance = 1, left =-1, right = -1;for (int i = 0; i < bucket.length; i++) {if (bucket[i][1] = = 1) continue;if (right = =-1) {right = Bucket[i][1];continue;} left = Bucket[i][0];maxdistance=math.max (MaxDistance, left-right); right=bucket[i][1];} return maxdistance;    }

Java for Leetcode 163 Maximum Gap

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.