最小化数对的最大差值
难度:
标签:
题目描述
You are given a 0-indexed integer array nums
and an integer p
. Find p
pairs of indices of nums
such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p
pairs.
Note that for a pair of elements at the index i
and j
, the difference of this pair is |nums[i] - nums[j]|
, where |x|
represents the absolute value of x
.
Return the minimum maximum difference among all p
pairs. We define the maximum of an empty set to be zero.
Example 1:
Input: nums = [10,1,2,7,1,3], p = 2 Output: 1 Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
Example 2:
Input: nums = [4,2,1,2], p = 1 Output: 0 Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= p <= (nums.length)/2
代码结果
运行时间: 205 ms, 内存: 30.4 MB
import java.util.Arrays;
/**
* The idea is the same as the standard Java solution, but here we use streams for sorting and handling operations.
*/
public class Solution {
public int minimizeMaxDifference(int[] nums, int p) {
nums = Arrays.stream(nums).sorted().toArray();
int left = 0, right = nums[nums.length - 1] - nums[0];
while (left < right) {
int mid = (left + right) / 2;
if (canFormPairs(nums, p, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private boolean canFormPairs(int[] nums, int p, int maxDiff) {
int count = 0;
for (int i = 1; i < nums.length && count < p; i++) {
if (nums[i] - nums[i - 1] <= maxDiff) {
count++;
i++; // skip the next element
}
}
return count >= p;
}
}
解释
方法:
首先将数组排序,然后计算相邻元素的差值存入diff数组。如果p为0,则直接返回0。定义一个检查函数check,用于检查是否能找到p个差值小于等于upper的数对。使用二分查找在diff的最小值和最大值之间寻找满足条件的最小upper值,并返回该值加上diff的最小值作为结果。
时间复杂度:
O(nlogn)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在实现中首先对数组进行排序?排序对结果的正确性和算法的效率有什么影响?
▷🦆
在构建diff数组时,为什么只计算了相邻元素之间的差值?这样做是否能保证找到全局最优的下标对?
▷🦆
check函数中为什么要每次跳过一个元素(`i += 2`)来计数满足条件的对?这样做是否能保证不重复使用任何下标?
▷🦆
二分查找的目的是寻找满足条件的最小upper值,但为什么最终返回的结果是`ans = bisect_left(...) + min(diff)`,加上min(diff)的原因是什么?
▷