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;
    }
}
相關文章
相關標籤/搜索