LeetCode910. 最小差值 II

910. Smallest Range II

[Medium] 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. 1 <= A.length <= 10000
  2. 0 <= A[i] <= 10000
  3. 0 <= K <= 10000

題目:給定一個整數數組 A,對於每個整數 A[i],我們可以選擇 x = -K 或是 x = K,並將 x 加到 A[i] 中。在此過程之後,我們得到一些數組 B。返回 B 的最大值和 B 的最小值之間可能存在的最小差值。

思路:參考link。對於長度爲n的數組A,首先將其排序,則此時最大最小值之間的差值res爲末元素值減去首元素值。考慮不同的切分點,將排序後的數組分爲兩部分,因爲目的是希望差值儘量小,因此對左半數組進行加K運算,右半數組-K運算,得到對應的差值。

工程代碼下載 Github

class Solution {
public:
    int smallestRangeII(vector<int>& A, int K) {
        int n = A.size();
        sort(A.begin(), A.end());
        int left = A[0] + K, right = A[n-1] - K;
        int res = A[n-1] - A[0];
        for(int i = 0; i < n-1; ++i){
            int maxi = max(A[i]+K, right);
            int mini = min(left, A[i+1]-K);
            res = min(res, maxi - mini);
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章