2019-01-22

LeetCode 209. Minimum Size Subarray Sum.jpg

LeetCode 209. Minimum Size Subarray Sum

Description

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

描述

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。

示例:

输入: s = 7, nums = [2,3,1,2,4,3]
输出: 2
解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。
进阶:

如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。

思路

  • 使用两个指针left和right,用_sum来表示当前的和. right不断向右移动,_sum累加,当_sum大于等于s的时候,left向右移动直到_sum小于s,有效长度为right-left+2,返回所有有效长度的最小值即可.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-22 11:37:16
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-22 11:37:16

import sys


class Solution:
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        # 初始化长度
        length = sys.maxsize
        _sum, left, right = 0, 0, 0
        while right < len(nums):
            _sum += nums[right]
            # 如果当前的和已经大于等于s
            if _sum >= s:
                # 我们将左指针向右移动,和小于s时跳出
                while _sum >= s and left <= right:
                    _sum -= nums[left]
                    left += 1
                # 更新长度
                length = min(right - left + 2, length)
            right += 1
        # 如果length始终没有发生改变返回0,否则返回length本身
        return length if length != sys.maxsize else 0

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,682评论 0 10
  • 在一个偏僻遥远的山谷里,有一个高达数千尺的断崖。不知道什么时候,断崖边上长出了一株小小的百合。百合刚长出来的...
    清溪74阅读 368评论 0 0
  • 一,什么是聚合支付? 1,微信,支付宝支付为第三方支付;基于并整合微信支付宝等多种第三方支付平台,并提供支付技术和...
    Linda666888阅读 1,933评论 4 43
  • 1:每天安排时间时不要排那么满,留下缓存时间可以做额外的事。比如看到不错的文章可以利用当天或第二天的缓冲时间录下来...
    飞雪_飘渺阅读 158评论 0 0

友情链接更多精彩内容