搜索
首页web前端js教程面试工具包:数组 - 滑动窗口。

一切都与模式有关!

一旦你学会了这些模式,一切都开始变得更容易了!如果你像我一样,你可能不喜欢技术面试,我不怪你——面试可能很艰难。

数组问题是面试中最常见的问题。这些问题通常涉及使用自然数组:

const arr = [1, 2, 3, 4, 5];

还有字符串问题,本质上是字符数组:

"mylongstring".split(""); // ['m', 'y', 'l', 'o','n', 'g', 's','t','r','i', 'n', 'g']


解决数组问题最常见的模式之一是滑动窗口

滑动窗口模式

滑动窗口模式涉及两个沿同一方向移动的指针,就像在数组上滑动的窗口一样。

何时使用它

当您需要查找满足特定条件(例如最小值、最大值、最长或)的子数组子字符串时,请使用滑动窗口模式最短。

规则1:如果需要查找子数组或子字符串,并且数据结构是数组或字符串,请考虑使用滑动窗口模式。

简单的例子

这是一个介绍滑动窗口中指针概念的基本示例:

function SlidingWindow(arr) {
    let l = 0;  // Left pointer
    let r = l + 1;  // Right pointer

    while (r 



<p>请注意,左(L)和右(R)指针不必同时移动,但必须朝同一方向移动。</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172552892845227.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Interview Kit: Arrays - Sliding window."></p>

<p>右指针永远不会低于左指针。</p>

<p>让我们通过一个真实的面试问题来探索这个概念。</p>

<h3>
  
  
  现实问题:不重复字符的最长子串
</h3>

<p><strong>问题:</strong>给定一个字符串 s,找到不包含重复字符的最长子字符串的长度。</p>

<p><strong>关键字:</strong> <em>子</em>-字符串,最长(最大)<br>
</p>

<pre class="brush:php;toolbar:false">function longestSubstr(str) {
    let longest = 0;
    let left = 0;
    let hash = {};

    for (let right = 0; right = left) {
            left = hash[str[right]] + 1;
        }

        hash[str[right]] = right;
        longest = Math.max(longest, right - left + 1);
    }

    return longest;
}

如果这看起来很复杂,请不要担心——我们会一点一点地解释它。

let str = "helloworld";
console.log(longestSubstr(str));  // Output: 5

这个问题的核心是找到最长的子串没有重复字符。

初始窗口:大小 0

开始时,左(L)和右(R)指针都位于同一位置:

let left = 0;

for (let right = 0; right 





<pre class="brush:php;toolbar:false">h e l l o w o r l d 
^
^
L
R

我们有一个空的哈希(对象):

let hash = {};

物体有什么伟大之处?它们存储唯一的,这正是我们解决这个问题所需要的。我们将使用哈希来跟踪我们访问过的所有字符,并检查我们之前是否见过当前字符(以检测重复项)。

通过查看字符串,我们可以直观地看出world是最长的没有重复字符的子串:

h e l l o w o r l d 
          ^        ^   
          L        R

它的长度为 5。那么,我们如何到达那里?

让我们一步步分解:

初始状态

hash = {}

h e l l o w o r l d 
^
^
L
R

迭代 1:

在每次迭代中,我们将 R 指针下的字符添加到哈希映射中并递增:

hash[str[right]] = right;
longest = Math.max(longest, right - left + 1);

目前,我们的窗口中没有重复字符(h 和 e):

hash = {h: 0}
h e l l o w o r l d 
^ ^
L R

迭代 2:

hash = {h: 0, e: 1}
h e l l o w o r l d 
^   ^
L   R

现在,我们有一个新窗口:hel。

迭代 3:

hash = {h: 0, e: 1, l: 2}
h e l l o w o r l d 
^     ^
L     R

这就是有趣的地方:我们的哈希中已经有 l,而 R 指向字符串中的另一个 l。这就是我们的 if 语句的用武之地:

if (hash[str[right]] !== undefined)

如果我们的散列包含 R 指向的字母,我们就发现了一个重复项!上一个窗口 (hel) 是我们迄今为止最长的窗口。

那么,接下来我们该做什么?因为我们已经处理了左子字符串,所以我们通过向上移动 L 指针来从左侧缩小窗口。但我们要把 L 移动多远?

left = hash[str[right]] + 1;

我们将 L 移到重复项之后:

hash = {h: 0, e: 1, l: 2}
h e l l o w o r l d 
      ^
      ^
      L
      R

我们仍然将重复项添加到哈希中,因此 L 现在的索引为 3。

hash[str[right]] = right;
longest = Math.max(longest, right - left + 1);

新状态:迭代 4

hash = {h: 0, e: 1, l: 3}
h e l l o w o r l d 
      ^ ^
      L R

迭代 4 至 6

hash = {h: 0, e: 1, l: 3, o: 4, w: 5}
h e l l o w o r l d 
      ^     ^
      L     R

当 R 指向另一个重复项 (o) 时,我们将 L 移动到第一个 o 之后:

hash = {h: 0, e: 1, l: 3, o: 4, w: 5}
h e l l o w o r l d 
          ^ ^
          L R

我们继续,直到遇到另一个重复的 l:

hash = {h: 0, e: 1, l: 3, o: 4, w: 5, o: 6, r: 7}
h e l l o w o r l d 
          ^     ^
          L     R

但请注意它在当前窗口之外!从 w 开始,

规则 3:忽略已处理的子 x

当前窗口之外的任何内容都是无关紧要的——我们已经处理了它。管理这个的关键代码是:

if (hash[str[right]] !== undefined && hash[str[right]] >= left)

此条件确保我们只关心当前窗口内的字符,过滤掉任何噪音。

hash[str[right]] >= left

我们关注任何大于或等于左指针的东西

最终迭代:

hash = {h: 0, e: 1, l: 8, o: 4, w: 5, o: 6, r: 7}
h e l l o w o r l d 
          ^       ^
          L       R

我知道这很详细,但是将问题分解为更小的模式或规则是掌握它们的最简单方法。

In Summary:

  • Rule 1: Keywords in the problem (e.g., maximum, minimum) are clues. This problem is about finding the longest sub-string without repeating characters.
  • Rule 2: If you need to find unique or non-repeating elements, think hash maps.
  • Rule 3: Focus on the current window—anything outside of it is irrelevant.

Bonus Tips:

  • Break down the problem and make it verbose using a small subset.
  • When maximizing the current window, think about how to make it as long as possible. Conversely, when minimizing, think about how to make it as small as possible.

To wrap things up, here's a little challenge for you to try out! I’ll post my solution in the comments—it’s a great way to practice.

Problem 2: Sum Greater Than or Equal to Target

Given an array, find the smallest subarray with a sum equal to or greater than the target(my solution will be the first comment).

/**
 * 
 * @param {Array<number>} arr 
 * @param {number} target 
 * @returns {number} - length of the smallest subarray
 */
function greaterThanOrEqualSum(arr, target){
   let minimum = Infinity;
   let left = 0;
   let sum = 0;

   // Your sliding window logic here!
}

</number>

Remember, like anything in programming, repetition is key! Sliding window problems pop up all the time, so don’t hesitate to Google more examples and keep practicing.

I’m keeping this one short, but stay tuned—the next article will dive into the two-pointer pattern and recursion (prepping for tree problems). It’s going to be a bit more challenging!

If you want more exclusive content, you can follow me on Twitter or Ko-fi I'll be posting some extra stuff there!

Resources:

Tech interview Handbook

leet code arrays 101

以上是面试工具包:数组 - 滑动窗口。的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境