0910. Smallest Range II (M)

Smallest Range II (M)

题目

Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).java

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.this

Example 1:code

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:it

Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]

Note:io

  1. 1 <= A.length <= 10000
  2. 0 <= A[i] <= 10000
  3. 0 <= K <= 10000

题意

遍历一个数组,对每一个值进行加K或减K的操做,求获得的新数组中(max-min)的最小值。class

思路

由于每一个元素都必须加K或者减K,能够将数组分红两组,一组全加K,一组全减K,很明显要让小的数加K,让大的数减K。所以能够先对数组排序,而后肯定一个分界点,让左边的子数组left所有加K,右边的子数组right所有减K;同时注意到,两个子数组中的最小值都是各自的第一个元素,最大值都是各自的最后一个元素,所以能够比较得出全局的最大值和最小值,再以此更新结果。遍历


代码实现

Java

class Solution {
    public int smallestRangeII(int[] A, int K) {
        int ans = Integer.MAX_VALUE;
        Arrays.sort(A);

        for (int len = 0; len <= A.length; len++) {
            int max = 0, min = 0;
            if (len == 0 || len == A.length) {
                max = A[A.length - 1];
                min = A[0];
            } else  {
                max = Math.max(A[len - 1] + K, A[A.length - 1] - K);
                min = Math.min(A[0] + K, A[len] - K);
            }
            ans = Math.min(ans, max - min);
        }

        return ans;
    }
}
相关文章
相关标签/搜索