leetcode 908. Smallest Range I ( Python )

349 阅读20分钟

描述

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 中的任何一个数字和 -K <= x <= K 中的任何一个数字相加,得到数组 B ,然后求 min(max(B)-min(B)),只要把所有的数字向中间靠拢。即 A 中的最小值 +K , 最大值 -K ,判断这样操作之后,能否有重叠,如果能重叠所求的结果就是 0;如果不能重叠,所求的结果就是两者的差值。时间复杂度为 O(N),空间复杂度为 O(1)。

解答

class Solution(object):
    def smallestRangeI(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        return max(max(A) - min(A) - 2 * K, 0)                  	      
		

运行结果

Runtime: 96 ms, faster than 84.36% of Python online submissions for Smallest Range I.
Memory Usage: 12.7 MB, less than 32.29% of Python online submissions for Smallest Range I.	

每日格言:不要慨叹生活底痛苦!慨叹是弱者 —— 高尔基

请作者喝吃饼干 支付宝

支付宝

微信

微信