有一个整形数组A,请设计一个复杂度为O(n)的算法,算出排序后相邻两数的最大差值。
程序员文章站
2022-03-13 12:50:42
...
有一个整型数组,请设计一个复杂度为O(n)的算法,算出排序后相邻两数的最大差值。
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. You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
给定未排序的数组,找到其排序形式中的连续元素之间的最大差值。
尝试在线性时间/空间中解决它。 如果数组包含少于2个元素,则返回0。 你可以假设数组中的所有元素都是非负整数,并且适合32位有符号整数范围。
Example 1:Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
public static int findMaxDivision(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
// 找出数组的最大值和最小值
int max = nums[0];
int min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
}
if (nums[i] > max) {
max = nums[i];
}
}
if (max == min) {
return 0;
}
int[] minA = new int[nums.length + 1]; // 存放每个桶中的最小值,最后一个桶刚好用来放最大值
int[] maxA = new int[nums.length + 1]; // 存放每个桶中的最大值
for (int i = 0; i < nums.length + 1; ++i) {
minA[i] = -1;
maxA[i] = -1;
}
double interval = (double) nums.length / (max - min);
for (int i = 0; i < nums.length; i++) { // 注意i的范围,不是nums.length+1,会越界
int tag = (int) ((nums[i] - min) * interval);
if (minA[tag] == -1) {
minA[tag] = nums[i];
maxA[tag] = nums[i];
} else {
minA[tag] = Math.min(minA[tag], nums[i]);
maxA[tag] = Math.max(maxA[tag], nums[i]);
}
}
// 找出第一个空桶的前一个桶的最大值和最后一个空桶的后一个桶的最小值
int result = 0;
int prev = maxA[0];
for (int i = 1; i < nums.length + 1; i++) {
if (minA[i] != -1) {
result = Math.max(result, minA[i] - prev);
prev = maxA[i];
}
}
return result;
}
本文参考:
https://blog.csdn.net/ifollowrivers/article/details/75330578
https://www.programcreek.com/2014/03/leetcode-maximum-gap-java/
https://leetcode.com/problems/maximum-gap/solution/