0910. Smallest Range II (M)
阿新 • • 發佈:2020-12-21
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)
.
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: 3
Explanation: B = [4,6,3]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
題意
遍歷一個數組,對每個值進行加K或減K的操作,求得到的新陣列中(max-min)的最小值。
思路
因為每個元素都必須加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; } }