当前位置:网站首页>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;}}边栏推荐
猜你喜欢
随机推荐
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
ansible模块--yum模块
How to connect TDengine through DBeaver?
Oracle降低高水位
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
使用kubesphere图形界面创建一个应用操作流程
The exchange - string dp
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
JSP中如何正确的填写include指令中的file路径呢?
Running yum reports Error: Cannot retrieve metalink for reposit
CAN总线的AUTOSAR网络管理
今日睡眠质量记录85分
您应该知道的 Google Sheets 使用技巧
npm run serve启动报错npm ERR Missing script “serve“
中原银行实时风控体系建设实践
19、商品微服务-srv层实现
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
力扣35-搜索插入位置——二分查找









