leetcode讲解–908. Smallest Range I

题目
Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
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: 0
Explanation: B = [3,3,3] or B = [4,4,4]
Note:

1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000

题目地址
讲解
这道题刚开始一直没看懂题,但是看懂了之后就会发现非常非常简单。题目的意思是对一个数组A中的每一个数,都加一个x,x的取值范围是-K <= x <= K,然后得到结果数组B,取B中的最大值和最小值,让这两者的差最小(最小是0),求这个最小值。
这里有个误区是所有数加的x都相同,但你仔细看题目给的例子,x并不是要相同的。
看完例子我们发现,只要A的最大和最小值之差小于2倍K,我们就能让B中的元素全部相等。这就是解题思路。
Java代码
class Solution {
public int smallestRangeI(int[] A, int K) {
int max=A[0];
int min=A[0];
for(int i=0;i<A.length;i++){
if(max<A[i]){
max = A[i];
}
if(min>A[i]){
min=A[i];
}
}
if(2*K>max-min){
return 0;
}else{
return max-min-2*K;
}
}
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理