After brushing the 12 sliding windows, you can tear the front end by hand

Kitchen ape gaga 2021-09-15 06:28:50
brushing sliding windows tear end


People often ask , As front-end , What algorithms have you used in your actual work , My answer was , Tree and bit operations , Recently, I am learning the network module , Found and front end , At least an algorithm related to the network , That's it The sliding window ;

We know that HTTP1.1 Send a request ,TCP The request will be transmitted to the server , And for TCP agreement , One of the most important capabilities is to control the flow rate ;

When the sender needs to send many requests , These requests will block waiting in a cache TCP send out , This is followed by a steady stream of requests , Then you can't plug it all in the cache at once , It'll blow up , At this time, the model is a sliding window


The sending process has three states :

  • Green is the of sending and connecting successfully
  • Light green is sending , But I haven't received ACK Responsive , It's possible to hang up at this time , So at this time, the sender must keep the request and be ready to resend it at any time
  • White is waiting to be sent
  • The latter are blocked requests

This is the time TCP The number of requests that can be cached is a window , Whenever light green turns dark green , Then the window can slide on the right , The state that the window still retains can still be reused , This is it. The sliding window The charm of

The biggest feature of sliding window is , During sliding window , The data state retained in the window is directly reused , No need to build again , Saving resource ;

Then let's get familiar with a slide window by doing questions , And see if there are more different situations ;


Finish this 20 A dichotomy , Maybe you can't tear your hands off a big factory interview

Finish these questions , Maybe you can't tear your hands off a big factory interview

Finish this 30 The problem of Dao tree , Maybe you can't tear your hands off a big factory interview

Finish this 20 List questions , Maybe you can't tear your hands off a big factory interview

Finish this 15 Avenue dp topic , I can only take a chance to enter the big factory

Finish this A few Trace bit operation , Wait and consider the interview with a big factory -- Failed the audit , We'll do it later


Depending on whether the sliding window size is fixed , There are two kinds of : Fixed size window and Variable window size ;

The preface talks about TCP Sliding window in , It's actually a fixed size sliding window , Of course, you can also give a part size first , Then expand according to the flow rate , That's the follow-up operation ;

More often, sliding windows of variable size , This kind of sliding window is generally created in the process , A brain runs out of resources to expand the window , Reaching a threshold , Then shrink the window , According to the specific topic , Reached a balance ;

It's like a quick trial and error process , First push the situation to the extreme , Then add the corresponding variable to shrink the window , Find a more suitable situation , Wait until the compliance situation breaks in the window , Just re expand ;

Sliding window is actually understanding the meaning of the question , It's a little split in two , That is, I can cut the state in the window from the state outside the window , But they are shift The relationship between , So keep weighing , Reach a state of dynamic balance , Is the result of some questions


Fixed size window

  • l Initialize to 0
  • initialization r, bring r-l+1 Is the window size
  • Move at the same time l and r
  • Judge whether the continuous elements in the window meet the conditions of the topic

Variable window size

  • l r All initialized to 0
  • r Move the pointer one step
  • Judge whether the continuous elements in the window meet the conditions
    • Satisfy , Then judge whether it is necessary to update the optimal solution ; Update... If necessary , And try to move l The pointer reduces the size of the window
    • dissatisfaction , Continued to

Double sliding window phenomenon

  • Ordinary sliding windows always go first r The pointer , Then the trigger condition is reached , And then contract l The pointer , Stop after the contraction fails to meet the standard , then r Pointer restart
  • But there are some problems , When r After the pointer reaches the standard , l The pointer is within a range [l1,l2), And may be related to subsequent [r1,r2) Any sliding window consisting of two pointers will constitute a compliant sliding window
  • Then use a single pointer at this time l Shrink to unsatisfactory l2, Then only [l1,l2) And r1 Conditions , And what should have been compliant lx-rx All killed (lx stay [l1,l2] in ), Because at this time l Has run to l2 It's too late
  • At this time, you need to open two pointers l1, l2 , Fixed every time r When the pointer , Let's find the first one that meets the requirements l1, And cut-off position l2, Then continue to let r go , Always keep two sliding windows during movement [l1.r],[l2,r], It can ensure that all situations are taken into account in the whole movement process
  • This kind of problem is to seek quantity , For example How many subarrays are there in a certain case , So you have to get everything out , But if only an extreme value is required , For example, in these cases that meet the requirements , What's the minimum , Then there's no need to use double sliding windows , because r The movement of the pointer will certainly enlarge the window , therefore l The pointer only needs to keep the corresponding extreme value ( First or last ), Then find the extreme value

The matching title is 930. And the same binary subarray

992. K Sub array of different integers

1248. Statistics 「 Graceful subarray 」


Sliding window is a special case of double pointer , When we use double pointers to deal with problems , The status value in the previous window may not be considered , Just consider all the circumstances , In this way, many calculations are repeated , Sliding window is an optimized double pointer case .

So the algorithm is still a little useful , At least at the beginning , We can better understand the kernel of the tools we use , Not just looking at flowers in the fog , Know what it is and don't know why it is ;

So come on !!

List of topics

Fixed window

Unfixed window

本文为[Kitchen ape gaga]所创,转载请带上原文链接,感谢

  1. Flutter: résoudre le futur blocage en utilisant Isolate
  2. Résumé des opérations courantes pour les données de structure de l'arbre frontal
  3. Ant Design Transfer Twin Tree Shuttle box "make Wheels"
  4. De la carte de pensée à la base et à l'approfondissement, prenez note de l'expérience d'entrevue d'un octet sautant le poste de recherche et développement Java.
  5. Apprenez les composants d'implémentation de vue et Publiez - les à NPM
  6. [Questions d'entrevue à haute fréquence] À vous de choisir
  7. Une faible connaissance de beginpath () provoque une superposition de style lors de la peinture d'un dessin en toile
  8. React Hooks, laisse - moi t'emmener étudier.
  9. Comment la copie profonde résout - elle les références circulaires?
  10. JavaScript Advanced Programming (3rd Edition) Reading note 6
  11. Analyse de l'URL
  12. Discussion préliminaire sur xss
  13. Solution: développement de la page Web Wechat, obtenir la fosse Piétinée par le flux d'entrée de la caméra via navigator.mediadevice.getusermedia ()
  14. Des milliers de questions d'entrevue sélectionnées n'ont pas encore ét é effacées.
  15. Les questions d'entrevue de niveau intermédiaire et avancé d'Android au fil des ans sont entièrement incluses, et l'algorithme est distribué microservice
  16. J'ai résumé toutes les questions d'entrevue.
  17. Compréhension de la réactivité des données de vue
  18. Note de service CSS (vi): Flex, page mobile et mise en page réactive
  19. Non-ASCII character ‘\xe5‘ in file on line 4, but no encoding declared; see http://python.or
  20. 手把手教你搭建微信小程序服务器(HTTPS)
  21. JavaScript Review sketch - 1
  22. Analyse du bootstrap webpack
  23. sqli-labs-less-18 http头user agent+报错注入
  24. Génération de code nest pour l'outil CLI de nestjs
  25. JS | This
  26. Augmentation des variables
  27. The sinking gs8 raises its flag again. GAC motor's sales are falling endlessly. Is it the car or the people?
  28. Ren Hao's lunch at work today is president Hao wearing a sleeveless coat! Clean and handsome!
  29. Summary of basic knowledge points of JavaScript language (mind map)
  30. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  31. Sqli Labs - less - 18 http header user agent + Error Reporting Injection
  32. Vous apprendrez à construire un serveur d'applet Wechat (https) à la main
  33. Non - ASCII character 'xe5' in file on Line 4, but no Encoding declared;Voirhttp://python.or
  34. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  35. En tant que programmeur, quelle est la plus grande tristesse que vous ressentez? L'entrevue d'emploi Java de 2021 dans une grande usine vous demandera:
  36. En tant que programmeur, je n'oublie pas le dernier résumé de mon expérience d'entrevue de stage en Java.
  37. Experts suggested that performers work with certificates, which triggered a collective heated debate. It is meaningless to be accused of repeating the mistakes
  38. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  39. The appearance value of 200000 "Odyssey" is less than 100000, and has become the "sales champion" of household MPV
  40. Les programmeurs Java qui sont entrés dans l'entreprise pendant trois mois ont dû faire face à une correction d'échelle, et les octets ont sauté dans le traitement des questions d'entrevue de JD 360 Netease.
  41. 350 questions d'entrevue Android partage, technologie d'architecture de cache
  42. The space is not vulgar, the configuration is rich, the leather is durable, less worry, and the high configuration is less than 100000!
  43. Vous permet de passer rapidement à travers l'entrevue de saut d'octets et d'aller de l'avant
  44. Résumé des questions d'entrevue technique d'Alibaba Baidu et d'autres grandes usines à la fin de l'année, et analyse de la dernière vraie question d'entrevue Android en 2021
  45. Avec cet ensemble de questions d'entrevue Java, l'ensemble de questions de base d'entrevue de bat,
  46. Avec cet ensemble de questions d'entrevue Java, les notes avancées Java de niveau divin sont systématisées,
  47. Opérateurs arithmétiques et opérateurs de comparaison pour JavaScript, Introduction classique au développement web
  48. Explorer le cadre open source Android - 1. Okhttp Source Analysis
  49. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  50. Partager l'expérience de l'examen et du développement de l'arrière - plan, en s'appuyant sur les questions d'entrevue et les réponses,
  51. Site Web pour partager vos expériences d'entrevue, Tencent Bull vous apprend à écrire votre propre cadre Java!
  52. Notes d'étape Android structurées, sélection de vrais problèmes d'entrevue Android
  53. Dictionnaire distribué: communication de cache limitée par le courant, sujets d'entrevue pour certaines questions courantes dans le développement Java,
  54. Tianci girlfriend Tangyuan attended the event for the second time. Her appearance was comparable to that of a star. The audience shouted that Tianci was blessed!
  55. Introduction au JavaScript chapitre 15 (objets, clairvoyance)
  56. La dernière revue scientifique de l'académicien Luo Liqun: architecture de la boucle neuronale pour stimuler la nouvelle Ia
  57. Basic knowledge of components in Vue "I"
  58. J'a i appris quelques petites choses sur l'entrevue et j'ai acheté un tutoriel en 19998.
  59. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  60. Want to know the implementation and application of single instance mode in the front end?