博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode之Minimum Size Subarray Sum
阅读量:2343 次
发布时间:2019-05-10

本文共 1219 字,大约阅读时间需要 4 分钟。

题目描述如下:

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

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

求满足和大于等于某个数的最小子数组长度,脑子还是太笨。。
暴力法会TLE,大家都知道。。
于是又上网搜了其他的解法,设置双指针,一前(start)一后(end),end指针往后移动知道sum >=s,然后start指针往后移动,使其在满足sum >= s的条件下不断缩小数组长度;

python代码如下:

class Solution(object):    def minSubArrayLen(self, s, nums):        """        :type s: int        :type nums: List[int]        :rtype: int                """                if nums == None or len(nums) == 0:            return 0                min_length = 0         sum = 0        start = end = 0                while start < len(nums) and end < len(nums):            while end < len(nums) and sum < s:                sum += nums[end]                end += 1                        while sum >= s and start <= end:                if min_length == 0:                    min_length = end - start                else:                    min_length = min(min_length, end - start)                sum -= nums[start]                start += 1                return min_length

转载地址:http://mmbvb.baihongyu.com/

你可能感兴趣的文章
校招上机题(收集)
查看>>
大量数据如何排序
查看>>
org.mybatis.spring.MyBatisSystemException(参数找不到问题)
查看>>
JQuery+JQuery ui实现的弹出窗口
查看>>
jQuery怎么获取<c:forEach>标签的值
查看>>
程序员应该知道的福利
查看>>
Java日期时间处理
查看>>
包装类
查看>>
Object/System/RunTime类
查看>>
字符串类/正则表达式
查看>>
看完不敢熬夜了
查看>>
Java异常处理
查看>>
JQueryUI实现对话框
查看>>
Java流(Stream)/文件(File)/IO
查看>>
文件处理(压缩与解压)
查看>>
Java中的目录
查看>>
JQuery实现对select选择框的赋值
查看>>
JavaNIO学习(与IO比较)
查看>>
SweetAlert插件
查看>>
Java开发者必读的10篇精选优秀技术文章
查看>>