当前位置:网站首页>The sliding window of the force button "step by step" (209. sub array with the smallest length, 904. fruit basket)
The sliding window of the force button "step by step" (209. sub array with the smallest length, 904. fruit basket)
2022-06-23 08:58:00 【Endless learning java】
Sliding window of force buckle Brush step by step (209. Subarray with the smallest length 、904. Fruit baskets )

So called sliding window , It's constantly adjusting the starting and ending positions of subsequences , So we can get the result that we want to think about . Double pointer for
The first question is simple
Strengthen the second medium question
The first question is 209. Subarray with the smallest length
Given a containing n An array of positive integers and a positive integer s , Find the sum of the array ≥ s The smallest length of continuity
Subarray , And return its length . If there is no sub array that meets the conditions , return 0.Example :
Input :s = 7, nums = [2,3,1,2,4,3] Output :2 explain : Subarray [4,3] Is the smallest subarray in this condition .
In this topic, we realize the sliding window , The main points are as follows :
- What's in the window ?
- How to move the start of a window ?
- How to move the end of a window ?
The window is Satisfy it and ≥ s The smallest length of continuity Subarray .
How the start of the window moves : If the value of the current window is greater than s 了 , The window is about to move forward ( It's time to shrink ).
How the end of the window moves : The end of the window is the pointer that traverses the array , Set the starting position of the window as the starting position of the array .
It can be found that the subtlety of sliding window is based on the current subsequence and size , Constantly adjust the starting position of subsequences . So that O(n^2) The violent solution is reduced to O(n)
class Solution {
// The sliding window
public int minSubArrayLen(int s, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;// Express int Maximum , It's quite big 2 How many for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= s) {
result = Math.min(result, right - left + 1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
The second question is 904. Fruit baskets
You are visiting a farm , The farm planted a row of fruit trees from left to right . These trees use an array of integers fruits Express , among fruits[i] It's No i The fruit on the tree species .
You want to collect as much fruit as possible . However , The owner of the farm set some strict rules , You must pick the fruit as required :
You only have Two Basket , And each basket can only hold Single type The fruit of . There is no limit to the amount of fruit each basket can hold .
You can choose any tree to start picking , You have to go from Each tree Trees ( Including the trees that start picking ) On Just pick a fruit . The fruit picked should match the type of fruit in the basket . Every time you pick , You will move right to the next tree , And continue to pick .
Once you get to a tree , But the fruit doesn't match the type of fruit in the basket , Then you must stop picking .
Give you an array of integers fruits , Return the fruit you can collect Maximum number .
// The sliding window ( Double pointer ) The left pointer determines the condition The right pointer is responsible for traversing
class Solution {
public int totalFruit(int[] tree) {
if (tree == null || tree.length == 0) return 0;
int n = tree.length;
Map<Integer, Integer> map = new HashMap<>();
int maxLen = 0, left = 0;
for (int i = 0; i < n; i++) {
// There are three different fruit times
map.put(tree[i], map.getOrDefault(tree[i], 0) + 1);
while (map.size() > 2) {
map.put(tree[left], map.get(tree[left]) - 1);
// You can't directly remove, Because considering [3,3,3,1,...] This situation
// Otherwise 333 Delete it directly
if (map.get(tree[left]) == 0) map.remove(tree[left]);
left++;
}
maxLen = Math.max(maxLen, i - left + 1);
}
return maxLen;
}
}
explain map.
map.getOrDefault(Object key, V defaultValue);
①map in key,value return key Corresponding value that will do .
②map Does not exist in the key,value Then return to defaultValue( The default value is ).
map.put(num,map.getOrDefault(num, 0) + 1)
①map contains num Words , will num Corresponding value value +1
②map It does not contain num Words ,num Corresponding value The corresponding default value is assigned as 0, And then again +1
So this method is suitable for statistics num Number of occurrences
边栏推荐
- 'coach, I want to play basketball!'—— AI Learning Series booklet for system students
- Subsets of leetcode topic resolution
- Unique paths II of leetcode topic analysis
- Interpretation of the most dirty technology in history, I can understand 60 it terms in seconds
- Summary ranges of leetcode topic resolution
- Why is the easycvr Video Fusion platform offline when cascading with the Hikvision platform? How to solve it?
- [QNX Hypervisor 2.2用户手册]6.1 使用QNX Hypervisor系统
- [qnx hypervisor 2.2 user manual]5.6.1 silent device during guest shutdown
- The results of CDN node and source station are inconsistent
- Lighthouse cloud desktop experience
猜你喜欢

“教练,我想打篮球“ —— 给做系统的同学们准备的 AI 学习系列小册

636. Exclusive Time of Functions

Keng dad's "dedication blessing": red packet technology explosion in Alipay Spring Festival Gala

力扣之滑动窗口《循序渐进》(209.长度最小的子数组、904. 水果成篮)

Linux Mysql安装

6月《中国数据库行业分析报告》发布!智能风起,列存更生

The fourth online workshop review

The most commonly used 5-stream ETL mode

通用分页(1)

【学习资源】理解数学和热爱数学
随机推荐
测试-- 自动化测试selenium(关于API)
636. Exclusive Time of Functions
What exactly is RT?
Assembly (receive several n-digit decimal values (0~65535) from the keyboard and display their sum in different base numbers.)
如何在 FlowUs、Notion 等笔记软件中使用矩阵分析法建立你的思维脚手架
[QNX Hypervisor 2.2用户手册]5.6.1 Guest关机时静默设备
[qnx hypervisor 2.2 user manual]6.1 using the QNX hypervisor system
How to sort a dictionary by value or key?
Mqtt+flink to subscribe and publish real-time messages
36氪首发|云原生数据库公司「拓数派」完成新一轮战略融资,估值已达准独角兽级别
Subsets II of leetcode topic analysis
How to restore visualizations and dashboards after kibana rebuilds the index
3. caller service call - dapr
USB peripheral driver - debug
986. Interval List Intersections
Only 187 bytes of desktop dream code
[cloud computing] GFS ideological advantages and architecture
7-palette-calayer and touch
Happy number of leetcode topic analysis
Node request module cookie usage