Topic:
Given an array of shapes, ARR returns the maximum difference between two adjacent numbers after sorting.
The time complexity is O (N).
Answer:
If implemented by sorting, its time complexity is O (Nlogn), and if the idea of using bucket sequencing (not the bucket sort), you can do O (n), the additional space complexity is O (n). Traverse arr to find the maximum max and min values min. If Arr has a length of N, prepare n+1 buckets, place Max alone in the n+1 bucket, the number in the [Min,max] range is placed in the 1~n bucket, and for each bucket in the 1~n bucket, the responsible interval is (max-min)/n. If a number is num, it should be assigned into (num-min) *len/(max-min).
ARR has a total of n number, Min, will be put into the bucket 1th, Max will be put into the last bucket, so, if all the numbers into the n+1 bucket, there must be a bucket is empty. The number of neighbors that produce the maximum difference is from a different bucket. So as long as the interval between the number of buckets can be calculated, that is, only the maximum and minimum value of each bucket is recorded, the maximum difference may only come from the minimum value of a non-empty bucket minus the maximum value of the previous non-empty bucket.
Public Static int maxgap (int[] nums) {
if Null | | Nums.length < 2) {
return 0;
}
int len = nums.length;
int min = integer.max_value;
int max = Integer.min_value;
for (int i = 0; i < len; i++) {
min = math.min (min, nums[i]);
max = Math.max (max, nums[i]);
}
if (min = = max) {
return 0;
}
Boolean New Boolean [Len + 1];
int New int [Len + 1];
int New int [Len + 1];
int bid = 0;
for (int i = 0; i < len; i++) {
Figure out the bucket number.
Mins[bid] = Hasnum[bid]? Math.min (Mins[bid], nums[i]): Nums[i];
Maxs[bid] = Hasnum[bid]? Math.max (Maxs[bid], nums[i]): Nums[i];
true;
}
int res = 0;
int Lastmax = 0;
int i = 0;
while (I <= Len) {
if //Find the first non-empty bucket
Lastmax = Maxs[i-1];
break;
}
}
for (; I <= len; i++) {
if (Hasnum[i]) {
res = Math.max (res, mins[i]-Lastmax);
Lastmax = Maxs[i];
}
}
return Res;
}
The long type is used to prevent overflow when multiplying
Public Static int Bucket (long Long Long, max) {
return (int) ((num-min) * Len/(max-min));
}
The maximum difference of the number of neighbors after the [algorithm] array is sorted