当前位置:网站首页>The sliding window of Li Kou "step by step" (209. The smallest sub array, 904. Fruit baskets)
The sliding window of Li Kou "step by step" (209. The smallest sub array, 904. Fruit baskets)
2022-07-24 14:15: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
边栏推荐
- Csp2021 T1 corridor bridge distribution
- IEEE Transaction期刊模板使用注意事项
- Flink fault tolerance mechanism (V)
- 看完这篇文章,才发现我的测试用例写的就是垃圾
- On the number of solutions of indefinite equations
- Flink advanced features and new features (VIII)
- Rasa 3.x learning series -rasa fallbackclassifier source code learning notes
- Afnetworking data raw request mode
- OWASP ZAP安全测试工具使用教程(高级)
- Rasa 3.x learning series -rasa [3.2.3] - new version released on July 18, 2022
猜你喜欢

电赛设计报告模板及历年资源

How to quickly wrap lines in Excel table

OWASP zap security testing tool tutorial (Advanced)
![[oauth2] III. interpretation of oauth2 configuration](/img/31/90c79dbc91ee15c353ec46544c8efa.png)
[oauth2] III. interpretation of oauth2 configuration

About the flicker problem caused by using universalimageloader to load pictures and refresh data in recyclerview

OWASP ZAP安全测试工具使用教程(高级)

Mini examination - examination system

2022.7.22 simulation match

小熊派 课程导读

Centos7 installs Damon stand-alone database
随机推荐
数据湖系列文章
Flinktable & SQL (VII)
Nodejs uses the express framework to post the request message "badrequesterror:request aborted"
Apache2 ha experiment with raspberry pie
How to install PHP 5.6 on Ubuntu 18.04 and Debian 9
SQL server startup and shutdown job script
IntelliSense of Visual Studio: 'no members available'
Rasa 3.x 学习系列-Rasa FallbackClassifier源码学习笔记
Detailed explanation of switch link aggregation [Huawei ENSP]
Add an element to the object array with unshift
Flinktable & SQL (VI)
Stack and queue - 225. Implement stack with queue
Mini examination - examination system
Not configured in app.json (uni releases wechat applet)
OWASP ZAP安全测试工具使用教程(高级)
AtCoder Beginner Contest 261E // 按位思考 + dp
Click event to create a new node
Rhcsa sixth note
Error importing header file to PCH
Flink advanced features and new features (VIII) V2