class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int length = nums.size();
if (length == 0) {
return 0;
}
int left = 0;
int right = 1;
int ret = std::numeric_limits<int>::max();
int sum = nums[0];
while (right <= length and left < length) {
if (sum < s) {
if (right == length) {
break;
}
else {
sum += nums[right];
right += 1;
}
}
else {
ret = min(ret, right-left);
sum -= nums[left];
left += 1;
}
}
if (ret == std::numeric_limits<int>::max()) {
return 0;
}
else {
return ret;
}
}
};
standard solution
int minSubArrayLen(int s, vector<int>& nums)
{
int n = nums.size();
int ans = INT_MAX;
int left = 0;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
while (sum >= s) {
ans = min(ans, i + 1 - left);
sum -= nums[left++];
}
}
return (ans != INT_MAX) ? ans : 0;
Cautious
- Use ternary operator
网友评论