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).
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int ans = INT_MAX, sum = 0;
int st = 0, end = 0;
while (st < nums.size()) {
if (sum >= s) {
ans = min(ans, end - st);
sum -= nums[st++];
} else {
if (end == nums.size()) {
break;
}
sum += nums[end++];
}
}
return ans != INT_MAX ? ans : 0;
}
};
======= Another Older one =======
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int sum = 0;
int ans = INT_MAX;
int beg = 0;
if (nums.size() == 0) {
return 0;
}
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
if (sum >= s) {
ans = min(ans, i - beg + 1);
while (beg <= i && sum - nums[beg] >= s) {
sum -= nums[beg];
beg++;
ans = min(ans, i - beg + 1);
}
}
}
return (ans == INT_MAX ? 0: ans);
}
};
No comments:
Post a Comment