From 981d0323307f30f31d7eedac9309146377132717 Mon Sep 17 00:00:00 2001 From: raof01 Date: Thu, 8 Aug 2019 18:31:31 +0800 Subject: [PATCH] feat: #209: add C++ implementation (#89) --- problems/209.minimum-size-subarray-sum.md | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/209.minimum-size-subarray-sum.md b/problems/209.minimum-size-subarray-sum.md index 123bef33f..674b9d6af 100644 --- a/problems/209.minimum-size-subarray-sum.md +++ b/problems/209.minimum-size-subarray-sum.md @@ -31,6 +31,10 @@ If you have figured out the O(n) solution, try coding another solution of which ## 代码 +* 语言支持:JS,C++ + +JavaScript Code: + ```js /* * @lc app=leetcode id=209 lang=javascript @@ -93,6 +97,26 @@ var minSubArrayLen = function(s, nums) { }; ``` +C++ Code: +```C++ +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + int num_len= nums.size(); + int left=0, right=0, total=0, min_len= num_len+1; + while (right < num_len) { + do { + total += nums[right++]; + } while (right < num_len && total < s); + while (left < right && total - nums[left] >= s) total -= nums[left++]; + if (total >=s && min_len > right - left) + min_len = right- left; + } + return min_len <= num_len ? min_len: 0; + } +}; +``` + ## 扩展 如果题目要求是 sum = s, 而不是 sum >= s 呢?