题目链接
tag:
- Medium;
question:
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
思路:
这道题给定了我们一个数字,让我们求子数组之和大于等于给定值的最小长度,跟之前那道 Maximum Subarray 有些类似,并且题目中要求我们实现 O(n) 和 O(nlgn) 两种解法,那么我们先来看 O(n) 的解法,我们需要定义两个指针 left 和 right,分别记录子数组的左右的边界位置,然后我们让 right 向右移,直到子数组和大于等于给定值或者 right 达到数组末尾,此时我们更新最短距离,并且将 left 像右移一位,然后再 sum 中减去移去的值,然后重复上面的步骤,直到 right 到达末尾,且 left 到达临界位置,即要么到达边界,要么再往右移动,和就会小于给定值。代码如下:
// O(n)
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if (nums.empty()) return 0;
int left = 0, right = 0, sum = 0, len = nums.size(), res = len + 1;
while (right < len) {
while (sum < s && right < len) {
sum += nums[right++];
}
while (sum >= s) {
res = min(res, right - left);
sum -= nums[left++];
}
}
return res == len + 1 ? 0 : res;
}
};
网友评论