Maximum Gap@LeetCode

Maximum Gap

````java````public class Solution {
public int maximumGap(int[] num) {
if (num.length < 2)
return 0;
int minNum = num[0], maxNum = num[0], lengthOfNum = num.length;
for (int i = 1; i < lengthOfNum; i++) {
minNum = Math.min(minNum, num[i]);
maxNum = Math.max(maxNum, num[i]);
}
int step = (maxNum - minNum) / (lengthOfNum - 1);
step = step == 0 ? 1 : step;
int[] left = new int[(maxNum - minNum) / step + 1];
int[] right = new int[(maxNum - minNum) / step + 1];
for (int i = 0; i < lengthOfNum; i++) {
int range = (num[i] - minNum) / step;
if (range == left.length)
range--;
left[range] = left[range] == 0 ? num[i] : Math.min(left[range], num[i]);
right[range] = right[range] == 0 ? num[i] : Math.max(right[range], num[i]);
}
int maxGap = 0, leftMax = 0, rightMin = 0;
for (int i = 0; i < left.length; i++) {
if (left[i] == 0 && right[i] == 0)
continue;
if (leftMax == 0) {
leftMax = right[i];
continue;
}
rightMin = left[i];
maxGap = Math.max(maxGap, rightMin - leftMax);
leftMax = right[i];
}
return maxGap;
}
}
``````

1.1k 声望
63 粉丝
0 条评论