1、基数排序,然后根据排序后的数组找到相差的最大值。
public int maximumGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
// m is the maximal number in nums
int m = nums[0];
for (int i = 1; i < nums.length; i++) {
m = Math.max(m, nums[i]);
}
int exp = 1; // 1, 10, 100, 1000 ...
int R = 10; // 10 digits
int[] aux = new int[nums.length];
while (m / exp > 0) { // Go through all digits from LSB to MSB
int[] count = new int[R];
for (int i = 0; i < nums.length; i++) {
count[(nums[i] / exp) % 10]++;
}
for (int i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
for (int i = nums.length - 1; i >= 0; i--) {
aux[--count[(nums[i] / exp) % 10]] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = aux[i];
}
exp *= 10;
}
int max = 0;
for (int i = 1; i < aux.length; i++) {
max = Math.max(max, aux[i] - aux[i - 1]);
}
return max;
}
2、将数组分为n块,依次记录每一块的最大值和最小值,(最小值i-最大值i-1)的最大值即为所求(只有最小值i和最大值i-1是连续的)。例如:
index:0,1,2,3
val:2,8,7,9
maxA:2,MAX,8,9
minA:2,MIN,7,9
所以最大值就是7-2=5。
int maximumGap(vector<int>& nums) {
const int n = nums.size();
if(n<=1) return 0;
//get the max and min
int maxE = *max_element(nums.begin(),nums.end());
int minE = *min_element(nums.begin(),nums.end());
double len = double(maxE-minE)/double(n-1);
vector<int> maxA(n,INT_MIN);
vector<int> minA(n,INT_MAX);
// compute every block's min and max value
for(int i=0; i<n; i++) {
int index = (nums[i]-minE)/len;
maxA[index] = max(maxA[index],nums[i]);
minA[index] = min(minA[index],nums[i]);
}
//compute maxGap by minA[i]-maxA[i-1]
int gap = 0, prev = maxA[0];
for(int i=1; i<n; i++) {
if(minA[i]==INT_MAX) continue;
gap = max(gap,minA[i]-prev);
prev = maxA[i];
}
return gap;
}