[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].html

After this process, we have some array B.git

Return the smallest possible difference between the maximum value of B and the minimum value of B.github

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

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

Note:code

  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,這就是要求的答案啦,參見代碼以下:htm



解法一:blog

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 自帶的求最大值最小值的函數,從而一行搞定碉堡了~element



解法二:

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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索