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.

题目分析及思路

题目给出了一个整数数组A,要在[-K,K]区间内任意取一个数加到A[i]从而得到数组B;要求返回B中最大值和最小值差值的最小值。可以先对A从小到大排序,若最大值和最小值的差值比2K小,则一律返回0,否则则返回差值-2K。

python代码​

class Solution:

    def smallestRangeI(self, A, K):

        """

        :type A: List[int]

        :type K: int

        :rtype: int

        """

        A.sort()

        if A[-1] - A[0] >= 2 * K:

            return A[-1] - A[0] - 2 * K

        else:

            return 0

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10349665.html