当前位置:网站首页>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;}}
边栏推荐
- [kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
- 【Acunetix-忘记密码】
- 划分训练集,验证集,测试集
- npm run serve启动报错npm ERR Missing script “serve“
- 元宇宙“吹鼓手”Unity:疯狂扩局,悬念犹存
- Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
- Excel dynamic chart production
- 雷克萨斯,锁死的安全,挡不住的心寒
- excel 批量翻译-excel 批量函数公司翻译大全免费
- 【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
猜你喜欢
随机推荐
OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
Coroutines and Lifecycle in Kotlin
ansible模块--yum模块
AdguardHome如何配置设置?我的AdguardHome配置内容过滤器拦截列表
Mysql事务隔离级别与MVCC(多版本并发控制)
基于深度学习的裂缝检测技术
QT笔记——QT类反射机制简单学习
doc2vec和word2vec(zigbee简介及应用)
Golang map数组按字段分类
ssm网页访问数据库数据报错
华为eNSP(基础实验通信)
CAN总线的AUTOSAR网络管理
The sitcom "Re-Walking the Long March" was staged
SQL函数 $TRANSLATE
yolo格式(txt)数据集转VOC(xml)
翻译英语的软件-免费翻译软件-各种语言互相翻译
jvmxmx和xms参数分析(设定优化校准)
运行yum报错Error: Cannot retrieve metalink for reposit
记录代码
19、商品微服务-srv层实现