[LeetCode] 908. Smallest Range I 最小區間



Given an array `A` of integers, for each integer `A[i]` we may choose any `x` with `-K <= x <= K`, and add `x` to `A[i]`.

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: 0 Explanation: B = [3,3,3] or B = [4,4,4]

Note:

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

這道題說是給了一個非負數的數組,和一個非負數K,說是數組中的每一個數字都可以加上 [-K, K] 范圍內的任意一個數字,問新數組的最大值最小值之間的差值最小是多少。這道題的難度是 Easy,理論上應該是可以無腦寫代碼的,但其實很容易想的特別復雜。本題的解題標簽是 Math,這種類型的題目基本上就是一種腦筋急轉彎的題目,有時候一根筋轉不過來就怎么也做不出來。首先來想,既然是要求新數組的最大值和最小值之間的關系,那么肯定是跟原數組的最大值最小值有着某種聯系,原數組的最大值最小值我們可以很容易的得到,只要找出了跟新數組之間的聯系,問題就能迎刃而解了。題目中說了每個數字都可以加上 [-K, K] 范圍內的數字,當然最大值最小值也可以,如何讓二者之間的差值最小呢?當然是讓最大值盡可能變小,最小值盡可能變大了,所以最大值 mx 要加上 -K,而最小值 mn 要加上K,然后再做減法,即 (mx-K)-(mn+K) = mx-mn+2K,這就是要求的答案啦,參見代碼如下:
解法一:
class Solution {
public:
    int smallestRangeI(vector<int>& A, int K) {
        int mx = A[0], mn = A[0];
        for (int num : A) {
            mx = max(mx, num);
            mn = min(mn, num);
        }
        return max(0, mx - mn - 2 * K);
    }
};

我們也可以使用 STL 自帶的求最大值最小值的函數,從而一行搞定碉堡了~
解法二:
class Solution {
public:
    int smallestRangeI(vector<int>& A, int K) {
        return max(0, *max_element(A.begin(), A.end()) - K - (*min_element(A.begin(), A.end()) + K));
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/908


類似題目:

Smallest Range II


參考資料:

https://leetcode.com/problems/smallest-range-i/

https://leetcode.com/problems/smallest-range-i/discuss/173512/C%2B%2B-1-liner

https://leetcode.com/problems/smallest-range-i/discuss/173367/C%2B%2BJavaPython-Check-Max-Min


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM