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

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

题目:

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.

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

解法:两种解法,时间复杂度分别是O(N)和O(N*log(N))。

O(N)解法

思路:

使用两个指针i,j,分别指向开头,然后移动一个指针i,直到两个指针之间的数据和sum大于等于s,此时标记两个之间的数据个数min_len=i-j+1,然后使后一个指针j往前移动,此时重新判断两个指针之间的数据和sum是否大于等于s,不是的话往前移动i,是的话往前移动j,在移动过程中,凡是遇到sum和大于等于s,就判断i-j+1是否小于min_len,如果是,就更新min_len。直到最后两个指针都到达队尾结束(两个指针都是从头到尾,复杂度O(N))

class Solution {public:    int minSubArrayLen(int s, vector
& nums) { int len=nums.size(); int sum=0; if(len==0) return NULL; int i=-1,j=-1; int min_len=INT_MAX; bool flag=0; while(i<=len-1&&j<=len-1) { if(sum>=s) { j++; if(i-j+1

O(N*log(N))解法

题目非要整个N*log(N)的算法,好吧,就写个复杂点的,思路如下:

首先求出nums的累积分布和sums。

之后对sums的每个元素都进行遍历:sums[i]
如果sums[i]>=s,那么寻找使满足原数组中以i为结尾的,和大于等于s的最短连续序列的左下标。使用二分查找,复杂度是O(log(N))
由于上述是一个一个遍历,复杂度是O(N),所以总的复杂度是O(N*log(N))。

class Solution { public:    int minSubArrayLen(int s, vector
& nums) { int len=nums.size(); int sums[len+1]={
0}; int min_len=INT_MAX,left=0; for(int i=1;i<=len;i++) { sums[i]=sums[i-1]+nums[i-1];//累计求和 } for(int i=0;i<=len;i++) { left=Calleftindex(sums,i,s);//寻找sums中以i为结尾的大于等于s的最短左下标,复杂度log(N),二分查找 if(left!=INT_MAX&&i-left+1
=s) { left=mid+1; if(left>=max_left) max_left=left; } else { right=mid-1; } } return max_left; }};

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

你可能感兴趣的文章
【视频教程】Javascript ES6 教程28—ES6 Promise 实例应用
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(下)
查看>>
【web素材】03-24款后台管理系统网站模板
查看>>
Flex 布局教程:语法篇
查看>>
年薪50万+的90后程序员都经历了什么?
查看>>
2019年哪些外快收入可达到2万以上?
查看>>
【JavaScript 教程】标准库—Date 对象
查看>>
前阿里手淘前端负责人@winter:前端人如何保持竞争力?
查看>>
【JavaScript 教程】面向对象编程——实例对象与 new 命令
查看>>
我在网易做了6年前端,想给求职者4条建议
查看>>
SQL1015N The database is in an inconsistent state. SQLSTATE=55025
查看>>
RQP-DEF-0177
查看>>
Linux查看mac地址
查看>>
Linux修改ip
查看>>
MySQL字段类型的选择与MySQL的查询效率
查看>>
Java的Properties配置文件用法【续】
查看>>
JAVA操作properties文件的代码实例
查看>>
IPS开发手记【一】
查看>>
Java通用字符处理类
查看>>
文件上传时生成“日期+随机数”式文件名前缀的Java代码
查看>>