题目
Shortest Subarray with Sum at Least K
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
If there is no non-empty subarray with sum at least K, return -1.
Example 1:
Input: A = [1], K = 1
Output: 1
Example 2:
Input: A = [1,2], K = 4
Output: -1
Example 3:
Input: A = [2,-1,2], K = 3
Output: 3
Note:
1 <= A.length <= 50000-10 ^ 5 <= A[i] <= 10 ^ 51 <= K <= 10 ^ 9
Difficulty: Hard
分析过程
这个问题要求出所给数组中,所有数之和至少为K的子数组的最短长度。
暴力求解
建立 long int 类型的数组 sums ,sums[i] 表示前 i 个数的和。那么,就可以由 sums[j] - sums[i] 求出从第 i + 1 个数到第 j 个数的和了。这样只要遍历一次源数组,比对每个数对 ( i , j ) 都相加这个区间内的若干个数要高效。
然后,对每个数对 ( i , j ) ,都检查 sums[j] - sums[i] >= K 是否成立。时间复杂度是 O ( N 2 ) O(N^2) O(N

该博客介绍了LeetCode的一道题目,寻找数组中最短的连续子数组,使得其和至少为K。博主首先讨论了暴力求解的方法,然后通过优化算法,将时间复杂度降低到O(N),最终实现AC。文章强调了问题解决过程中的思考与总结的重要性。
最低0.47元/天 解锁文章
607

被折叠的 条评论
为什么被折叠?



