返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K 。
如果没有和至少为 K 的非空子数组,返回 -1 。
示例 1:
输入:A = [1], K = 1
输出:1
示例 2:
输入:A = [1,2], K = 4
输出:-1
示例 3:
输入:A = [2,-1,2], K = 3
输出:3
提示:
1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
类似题目:
LeetCode 974. 和可被 K 整除的子数组(哈希map)
class Solution {
public:
int shortestSubarray(vector<int>& A, int K) {
vector<int> presum(A.size()+1,0);
int i, minLen = INT_MAX, sum = 0;
deque<int> q;//存储下标,按照队内presum升序
q.push_back(0);//边界条件,前缀和为0,下标为0
for(i = 0; i < A.size(); ++i)
{
presum[i+1] = presum[i] + A[i];//前缀和
while(!q.empty() && presum[q.back()] >= presum[i+1])
q.pop_back();
while(!q.empty() && (presum[i+1]-presum[q.front()] >= K))
{
minLen = min(minLen, i+1-q.front());
q.pop_front();
}
q.push_back(i+1);
}
if(minLen == INT_MAX)
return -1;
return minLen;
}
};