当前位置:网站首页>Likou 209 - String with the Minimum Length - Sliding Window Method
Likou 209 - String with the Minimum Length - Sliding Window Method
2022-08-02 11:45:00 【Zhang Ran Ran √】
Title description
Given an array of n positive integers and a positive integer target .
Find the contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] with the smallest length in the array that satisfies its sum ≥ target, and return its length.Returns 0 if no matching subarray exists.
Solution ideas
- Cage's vivid sliding window solution;
- First create two pointers first and last to point to the head of nums;
- Move the right pointer, and consider whether the value between first------last meets the condition of >= target every time it moves;
- If not satisfied, last continues to move to the right;
- If it is satisfied, the first pointer moves to the right;
- Count the number of elements between first-----last that satisfy the condition each time, record the minimum value, and return the minimum value.
- When returning, you should add a judgment condition to see if the sum condition is met. If the sum condition is not met, and the minimum value is not updated, return 0.
Input and output example
Code
class Solution {public int minSubArrayLen(int target, int[] nums) {int len = nums.length;int first = 0;int sum = 0;int min = Integer.MAX_VALUE;for(int last = 0; last < len; last++){sum += nums[last];while(sum >= target){min = Math.min(min,last-first+1);sum -= nums[first++];}}return min == Integer.MAX_VALUE ? 0 : min;}}
边栏推荐
猜你喜欢
随机推荐
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
sva assertion data
Multithreading (Basic) - 40,000 word summary
SQL函数 TRIM
放苹果(暑假每日一题 13)
npm install报错npm ERR Could not resolve dependency npm ERR peer
今日睡眠质量记录85分
解决导出excel文件名中文乱码的问题
darknet训练yolov4模型
ssm网页访问数据库数据报错
The sitcom "Re-Walking the Long March" was staged
The exchange - string dp
find查找多类型结尾文件
When not to use () instead of Void in Swift
【Acunetix-忘记密码】
解决anaconda下载pytorch速度极慢的方法
Jest 测试框架 beforeEach 的设计原理解析
匹配滤波(四种滤波器的幅频特性)
免费文档翻译-免费批量文档翻译软件推荐
受邀出席Rust开发者大会|Rust如何助力量化高频交易?