一、题目描述
Given an array A of integers, for each integer A[i] we need to
choose either x = -K or x = K, and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between
the maximum value of B and the minimum value of B.
Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
二、题解
(1) 线性扫描:
先将数组nums
进行排序,然后以i
为分界点,把数组分为两个区间,他们分别为:
A[0]...A[i]
A[i+1]...A[N-1]
(N
为数组的元素的个数)
由上可得,以i为对称轴,分别将数组的两端的元素加上/减去K他们得到的状态为
- 最大值:
A[N-1]-k / A[i]+K
- 最小值:
A[0]+K / A[i+1]-K
基于以上的分析,我们只需要对最大最小值的两种可能进行比较即可得出真正的最大最小值,也就得到本次扫描的最小的最大值与最小值之差。
public int smallestRangeII(int[] A, int K) {
Arrays.sort(A);
int N = A.length;
int ans = A[N-1] - A[0];
int a = 0, b = 0;
for (int i = 0; i < N - 1; i++) {
a = A[i] + K;
b = A[i+1] - K;
int mayBeMax = Math.max(a, A[N-1]-K);
int mayBeMin = Math.min(b, A[0]+K);
ans = Math.min(ans, mayBeMax-mayBeMin);
}
return ans;
}
复杂度分析
- 时间复杂度:
O(N logN);
即Max(O(N logN), O(N))
,其中N
是A
的长度。 - 空间复杂度:
O(1)
,只使用了常数级别的额外空间。