当前位置:网站首页>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;}}
边栏推荐
- Oracle 19c 连接PDB
- Problem solving in the process of using mosquitto
- 阿苹的思考
- 当POC遇见RPA:RPA项目顺利实施的关键
- Create an application operation process using the kubesphere GUI
- Crack detection technology based on deep learning
- 【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
- 学习经验分享之七:YOLOv5代码中文注释
- Shell编程案例
- npm install报错npm ERR Could not resolve dependency npm ERR peer
猜你喜欢
随机推荐
暑期总结3
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
受邀出席Rust开发者大会|Rust如何助力量化高频交易?
SQLAlchemy使用教程
翁恺C语言程序设计网课笔记合集
打破千篇一律,DIY属于自己独一无二的商城
今日睡眠质量记录85分
Problem solving in the process of using mosquitto
使用kubesphere图形界面创建一个应用操作流程
ansible模块--yum模块
yolo格式(txt)数据集转VOC(xml)
Thymeleaf
pyqt5连接MYSQL数据库问题
sqli-labs(less-11)
使用mosquitto过程中的问题解决
力扣209-长度最小的字符串——滑动窗口法
SQL函数 TRIM
解决anaconda下载pytorch速度极慢的方法
划分训练集,验证集,测试集
学习经验分享之七:YOLOv5代码中文注释