Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
My solution is using the sliding window method. We use two pointers, left and right, to represent the left and right bound of the subarray. We move the right pointer to the right until the sum of the subarray is greater than or equal to the target. Then we move the left pointer to the right and update the minimun length of the subarray. We repeat the process until the right pointer reaches the end of the array.
classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int left = 0; int right = 0; int sum = 0; int minCount = INT_MAX; int n = nums.size(); while (right < n){ sum += nums[right]; right ++; while (sum >= target){ minCount = min(right - left, minCount); sum -= nums[left]; left ++; } } return (minCount == INT_MAX) ? 0 : minCount; } };