インタビュー キット: 配列 - スライディング ウィンドウ。

WBOY
リリース: 2024-09-05 17:35:25
オリジナル
1061 人が閲覧しました

重要なのはパターンです!

パターンを学ぶと、すべてが少し簡単に感じ始めます。あなたも私と同じなら、おそらく技術系の面接は好きではないでしょう。私はあなたを責めません。面接は厳しいものになる可能性があります。

配列の問題は、面接で遭遇する最も一般的な問題の 1 つです。これらの問題には、多くの場合、自然配列の操作が関係します。

const arr = [1, 2, 3, 4, 5];
ログイン後にコピー

そして、本質的に文字の配列である文字列の問題:

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


ログイン後にコピー

配列の問題を解決するための最も一般的なパターンの 1 つは、スライディング ウィンドウです。

スライディング ウィンドウ パターン

スライディング ウィンドウ パターンには、配列内をスライドするウィンドウのように、同じ方向に移動する 2 つのポインターが含まれます。

いつ使用するか

最小値、最大値、最長値など、特定の条件を満たす サブ配列 または サブ文字列 を検索する必要がある場合は、スライディング ウィンドウ パターンを使用します。最短です。

ルール 1: サブ配列またはサブ文字列を検索する必要があり、データ構造が配列または文字列である場合は、スライディング ウィンドウ パターンの使用を検討してください。

簡単な例

スライディング ウィンドウにポインターの概念を導入する基本的な例を次に示します。

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

    while (r < arr.length) {
        console.log("left", arr[l]);
        console.log("right", arr[r]);
        l++;
        r++;
    }
}

SlidingWindow([1, 2, 3, 4, 5, 6, 7, 8]);
ログイン後にコピー

左 (L) と右 (R) ポインターは同時に移動する必要はありませんが、同じ方向に移動する必要があることに注意してください。

Interview Kit: Arrays - Sliding window.

右ポインタが左ポインタよりも低くなることはありません。

実際の面接の問題でこの概念を探ってみましょう。

現実の問題: 繰り返し文字を含まない最長の部分文字列

問題: 文字列 s を指定して、文字を繰り返さない最長の部分文字列の長さを見つけます。

キーワード: サブ-文字列、最長 (最大)

function longestSubstr(str) {
    let longest = 0;
    let left = 0;
    let hash = {};

    for (let right = 0; right < str.length; right++) {
        if (hash[str[right]] !== undefined && hash[str[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 < str.length; right++) {  // RIGHT POINTER
ログイン後にコピー
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!
}

ログイン後にコピー

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!