美文网首页
209. Minimum Size Subarray Sum

209. Minimum Size Subarray Sum

作者: Ysgc | 来源:发表于2020-09-02 12:09 被阅读0次
    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            int length = nums.size();
            if (length == 0) {
                return 0;
            }
            
            int left = 0;
            int right = 1;
            int ret = std::numeric_limits<int>::max();
            int sum = nums[0];
    
            while (right <= length and left < length) {
                if (sum < s) {
                    if (right == length) {
                        break;
                    }
                    else {
                        sum += nums[right];
                        right += 1;
                    }
                }
                else {
                    ret = min(ret, right-left);
                    sum -= nums[left];
                    left += 1;
                }
            }
            
            if (ret == std::numeric_limits<int>::max()) {
                return 0;
            }
            else {
                return ret;
            }
        }
    };
    

    standard solution

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

    Cautious

    • Use ternary operator

    相关文章

      网友评论

          本文标题:209. Minimum Size Subarray Sum

          本文链接:https://www.haomeiwen.com/subject/bdoisktx.html