Keito

© 2024 Keito

技術ブログとポートフォリオ

2 pointer法

2つのポインタを使って配列を効率的に処理する重要な技法を学ぼう

O(n)
時間計算量
O(1)
空間計算量
中級
難易度
その他
カテゴリ

🔧 実行設定

操作:
twoSum
配列:
[2, 7, 11, 15]

💡 推奨操作

👆

アルゴリズムを実行してください

左側の設定パネルから操作を選択し、「アルゴリズム実行」ボタンを押してください

💻 実装例(JavaScript)

// Two Sum (ソート済み配列)
function twoSum(arr, target) {
    let left = 0, right = arr.length - 1;
    
    while (left < right) {
        const sum = arr[left] + arr[right];
        
        if (sum === target) {
            return [left, right];
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    
    return [-1, -1]; // 見つからない
}

// 配列の反転 (in-place)
function reverseArray(arr) {
    let left = 0, right = arr.length - 1;
    
    while (left < right) {
        [arr[left], arr[right]] = [arr[right], arr[left]];
        left++;
        right--;
    }
    
    return arr;
}

// 回文判定
function isPalindrome(s) {
    // 英数字のみを抽出して小文字化
    const processed = s.toLowerCase().replace(/[^a-z0-9]/g, '');
    let left = 0, right = processed.length - 1;
    
    while (left < right) {
        if (processed[left] !== processed[right]) {
            return false;
        }
        left++;
        right--;
    }
    
    return true;
}

// 重複除去 (ソート済み配列, in-place)
function removeDuplicates(arr) {
    if (arr.length === 0) return 0;
    
    let writeIndex = 1;
    
    for (let readIndex = 1; readIndex < arr.length; readIndex++) {
        if (arr[readIndex] !== arr[readIndex - 1]) {
            arr[writeIndex] = arr[readIndex];
            writeIndex++;
        }
    }
    
    return writeIndex; // 新しい長さ
}

// 使用例
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
console.log(reverseArray([1, 2, 3, 4, 5])); // [5, 4, 3, 2, 1]
console.log(isPalindrome("A man a plan a canal Panama")); // true