【LeetCode】【math】samllest range I
题目:
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
Runtime: 116 ms, faster than 84.00% of Python3 online submissions for Smallest Range I.
Memory Usage: 14.9 MB, less than 59.92% of Python3 online submissions for Smallest Range I.
参考答案:
思路相同,直接计算A中最大值和最小值的差值,优秀在于,如果A中最大值和最小值的差值<0,就可以直接判断所有值能否被调整到同一个数,即差值为0
但我不理解为什么会更慢呢???
class Solution(object): def smallestRangeI(self, A, K): return max(0, max(A) - min(A) - 2*K)
Runtime: 124 ms, faster than 48.83% of Python3 online submissions for Smallest Range I.
Memory Usage: 15 MB, less than 23.25% of Python3 online submissions for Smallest Range I.
-
Time Complexity: O(N)O(N)O(N), where NNN is the length of
A. -
Space Complexity: O(1)O(1)O(1).

浙公网安备 33010602011771号