C++實現LeetCode(209.最短子數組之和)

[LeetCode] 209. Minimum Size Subarray Sum 最短子數組之和

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).  

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

這道題給定瞭我們一個數字,讓求子數組之和大於等於給定值的最小長度,註意這裡是大於等於,不是等於。跟之前那道 Maximum Subarray 有些類似,並且題目中要求實現 O(n) 和 O(nlgn) 兩種解法,那麼先來看 O(n) 的解法,需要定義兩個指針 left 和 right,分別記錄子數組的左右的邊界位置,然後讓 right 向右移,直到子數組和大於等於給定值或者 right 達到數組末尾,此時更新最短距離,並且將 left 像右移一位,然後再 sum 中減去移去的值,然後重復上面的步驟,直到 right 到達末尾,且 left 到達臨界位置,即要麼到達邊界,要麼再往右移動,和就會小於給定值。代碼如下:

解法一:

// O(n)
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        if (nums.empty()) return 0;
        int left = 0, right = 0, sum = 0, len = nums.size(), res = len + 1;
        while (right < len) {
            while (sum < s && right < len) {
                sum += nums[right++];
            }
            while (sum >= s) {
                res = min(res, right - left);
                sum -= nums[left++];
            }
        }
        return res == len + 1 ? 0 : res;
    }
};

同樣的思路,我們也可以換一種寫法,參考代碼如下:

解法二:

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int res = INT_MAX, left = 0, sum = 0;
        for (int i = 0; i < nums.size(); ++i) {
            sum += nums[i];
            while (left <= i && sum >= s) {
                res = min(res, i - left + 1);
                sum -= nums[left++];
            }
        }
        return res == INT_MAX ? 0 : res;
    }
};

下面再來看看 O(nlgn) 的解法,這個解法要用到二分查找法,思路是,建立一個比原數組長一位的 sums 數組,其中 sums[i] 表示 nums 數組中 [0, i – 1] 的和,然後對於 sums 中每一個值 sums[i],用二分查找法找到子數組的右邊界位置,使該子數組之和大於 sums[i] + s,然後更新最短長度的距離即可。代碼如下:

解法三:

// O(nlgn)
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int len = nums.size(), sums[len + 1] = {0}, res = len + 1;
        for (int i = 1; i < len + 1; ++i) sums[i] = sums[i - 1] + nums[i - 1];
        for (int i = 0; i < len + 1; ++i) {
            int right = searchRight(i + 1, len, sums[i] + s, sums);
            if (right == len + 1) break;
            if (res > right - i) res = right - i;
        }
        return res == len + 1 ? 0 : res;
    }
    int searchRight(int left, int right, int key, int sums[]) {
        while (left <= right) {
            int mid = (left + right) / 2;
            if (sums[mid] >= key) right = mid - 1;
            else left = mid + 1;
        }
        return left;
    }
};

我們也可以不用為二分查找法專門寫一個函數,直接嵌套在 for 循環中即可,參加代碼如下:

解法四:

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int res = INT_MAX, n = nums.size();
        vector<int> sums(n + 1, 0);
        for (int i = 1; i < n + 1; ++i) sums[i] = sums[i - 1] + nums[i - 1];
        for (int i = 0; i < n; ++i) {
            int left = i + 1, right = n, t = sums[i] + s;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (sums[mid] < t) left = mid + 1;
                else right = mid - 1;
            }
            if (left == n + 1) break;
            res = min(res, left - i);
        }
        return res == INT_MAX ? 0 : res;
    }
};

討論:本題有一個很好的 Follow up,就是去掉所有數字是正數的限制條件,而去掉這個條件會使得累加數組不一定會是遞增的瞭,那麼就不能使用二分法,同時雙指針的方法也會失效,隻能另辟蹊徑瞭。其實博主覺得同時應該去掉大於s的條件,隻保留 sum=s 這個要求,因為這樣就可以在建立累加數組後用 2sum 的思路,快速查找 s-sum 是否存在,如果有瞭大於的條件,還得繼續遍歷所有大於 s-sum 的值,效率提高不瞭多少。

Github 同步地址:

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

類似題目:

Minimum Window Substring

參考資料:

https://leetcode.com/problems/minimum-size-subarray-sum/

https://leetcode.com/problems/minimum-size-subarray-sum/discuss/59090/C%2B%2B-O(n)-and-O(nlogn)

https://leetcode.com/problems/minimum-size-subarray-sum/discuss/59078/Accepted-clean-Java-O(n)-solution-(two-pointers)

到此這篇關於C++實現LeetCode(209.最短子數組之和)的文章就介紹到這瞭,更多相關C++實現最短子數組之和內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: