当前位置:网站首页>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;}}边栏推荐
猜你喜欢
随机推荐
微信小程序---组件开发与使用
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
MySQL主从复制几个重要的启动选项
SQL function $TRANSLATE
记录代码
使用无界队列的线程池会导致内存飙升吗?
【Acunetix-忘记密码】
npm run dev 和 npm run serve区别
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
小程序插件的生态丰富,加速开发建设效率
如何通过DBeaver 连接 TDengine?
Kotlin的协程与生命周期
力扣704-二分查找
元宇宙“吹鼓手”Unity:疯狂扩局,悬念犹存
go源码之sync.Waitgroup
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一
借小程序容器打造自有App小程序生态
JSP中如何正确的填写include指令中的file路径呢?
服务器间传输文件
图形处理单元(GPU)的演进









