题解 | #和大于等于K的最短子数组#
和大于等于K的最短子数组
http://www.nowcoder.com/practice/3e1fd3d19fb0479d94652d49c7e1ead1
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @param k int整型
* @return int整型
*/
int shortestSubarray(vector<int>& nums, int target) {
int l = -1;
int r = 0;
int sum = 0;
int max_v = nums.size();
while(r < nums.size()) {
if (sum < target) {
sum += nums[r];
++r;
} else {
max_v = min(max_v, r - l);
sum -= nums[l];
++l;
}
}
while(sum >= target) {
max_v = min(max_v, r - l);
sum -= nums[l];
++l;
}
if (l == -1) {
return l;
}
return max_v;
}
};