leetcode (Smallest Range I)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85697337

Title: Smallest Range I    908

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/smallest-range-i/

1.  见代码注释

时间复杂度:O(n),一次一层for循环,最长遍历长度为数组长度n。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 如果A中最大值减去最小值等于小于2K,最后B中的数都能是一样的,这样返回的为0
     * 如果A中最大值减去最小值大于2K,A中最小值加上负K,最大值加上K,然后做差值
     * @param A
     * @param K
     * @return
     */
    public static int smallestRangeI(int[] A, int K) {

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for (int a : A) {
            min = Math.min(min, a);
            max = Math.max(max, a);
        }

        return max - min > 2 * K ? max - min - 2 * K : 0;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85697337
今日推荐