title: Daily practice (45): sub-array with the smallest length
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/19
Daily practice (45): sub-array with the smallest length
Given an array of n positive integers and a positive integer target .
Find the smallest contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] in the array that satisfies its sum ≥ target and return its length. Returns 0 if no matching subarray exists.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
output: 2
Explanation: The subarray [4,3] is the subarray with the smallest length under this condition.
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
hint:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-size-subarray-sum
Method 1: Queue to simulate sliding window
Thought analysis
Use a queue to simulate a sliding window, and use a sum to record the sum of the numbers in the queue. Since the sizes of the numbers are different, here we use while to push out the numbers in the queue.
int minSubArrayLen(int target, vector<int>& nums) {
int ans = INT_MAX, sum = 0;
queue<int> que;
for (auto &n : nums) {
sum += n;
que.push(n);
while (sum >= target) {
ans > que.size() ? ans = que.size() : ans;
sum -= que.front();
que.pop();
}
}
return ans == INT_MAX ? 0 : ans;
}
Method 2: Double pointer
Thought analysis
Define two pointers i and j, and regard the interval [j, i] as a sliding window, then the two pointers represent the start position and end position of the sliding window respectively, and we maintain a sum variable to store the interval [ j,i] sum of consecutive arrays. If the interval and sum maintained by the current sliding window are greater than or equal to the target, it means that the current window is feasible, and the sliding window with the shortest length is the answer.
int minSubArrayLen(int target, vector<int>& nums) {
int res = INT_MAX, sum = 0;
for (int i = 0, j = 0; i < nums.size(); i++) {
sum += nums[i];//向右扩展窗口
while (sum - nums[j] >= target) {//向左收缩窗口
sum -= nums[j++];
}
if (sum >= target) {//区间更新
res = min(res, i - j + 1);
}
}
return res == INT_MAX ? 0 : res;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。