题解 | #和大于等于K的最短子数组#

和大于等于K的最短子数组

http://www.nowcoder.com/practice/3e1fd3d19fb0479d94652d49c7e1ead1

双指针, 右侧指针遍历直至和 s >= k 或者 r == n; 判断 s 的值,更新最小数组长度

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @param k int整型 
# @return int整型
#
class Solution:
    def shortestSubarray(self , nums: List[int], k: int) -> int:
        # write code here
        l = r = 0
        n = len(nums)
        min_l = float("inf")
        s = 0
        while l < n:
            while r < n and s < k:
                s += nums[r]
                r += 1
            if s >= k:
                min_l = min(min_l, r - l)
            s -= nums[l]
            l += 1
        return min_l if min_l != float("inf") else -1
全部评论
你确定能过吗。。题目没说a[i]一定大于0,你右指针往右,和反而可能越来越小
点赞 回复 分享
发布于 2022-03-26 17:03

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务