1. 程式人生 > >[LeetCode] Minimum Size Subarray Sum 最短子陣列之和

[LeetCode] Minimum Size Subarray Sum 最短子陣列之和

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

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

More practice:

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的值,效率提高不了多少。

類似題目:

參考資料: