题目:
A为一个给定的整数列表。对于A中每一个元素A[i],我们可以加上另一个数字x(-K <= x <= K)。
对A中所有元素进行了上述操作之后,求得到的新的数组B的最大值和最小值之间的最小差值。
example2:
Input:A = [0,10], K=2
Output:6
Explanation: B = [2,8]
example3:
Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]
Note:
1<=A.length<=10000
1<=A[i]<=10000
1<=K<=10000
本人解法:
最难的是读题/(ㄒoㄒ)/~~
因为求的是最小差值,最理想的情况是0,即所有值能否被调整到同一个数,即满足small + K >= (small+big)/2
其它情况,就是直接计算A中最大值和最小值的差值了。
class Solution: def smallestRangeI(self, A: List[int], K: int) -> int: big, small = max(A), min(A) if small + K >= (small+big)/2: #或是if min(A) + K > = max(A)-K: return 0 return big-small-K*2
class Solution(object): def smallestRangeI(self, A, K): return max(0, max(A) - min(A) - 2*K)
Time Complexity: O(N)O(N)O(N), where NNN is the length of A
.
Space Complexity: O(1)O(1)O(1).
【LeetCode】【math】samllest range I
原文:https://www.cnblogs.com/jialinliu/p/13186518.html