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