Leetcode Study Day 15

Minimum Size Subarray Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Example 1:

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

Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0


Constraints:

1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104

My solution

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int minSubArrayLen(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;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信