森田賢二のleetCodeの使い方、解説、解答を毎日更新しているキャラクター

[leetcode]問題解答と解説。2369. Check if There is a Valid Partition For The Array [JavaScript]

[leetcode]問題解答と解説。2369. Check if There is a Valid Partition For The Array [JavaScript]

皆さんleetCode好きですよね。私も好きです。
なかなかやる機会がないのですよね。
leetCodeの使い方や解説ではなく実際に問題を解決するために何をしたか
をメモ書きして行きます

私はある決意をして今挑んでいます。
モチベーションを保つためだけにこれをやっています。

では今日のleetCode。
【2369. Check if There is a Valid Partition For The Array】の解決策と方法。自分がまず挑戦して
やったことをさらけ出します。

※下にある自分のコードは自分で設けた制限時間内に書けたところまです。

これは
「私は年末までこれを続けたらどんなleetCoderになるか」のシリーズ。
実験的ブログ更新です。

森田賢二のleetCode
森田賢二のleetCode

2369. Check if There is a Valid Partition For The Array ルール

exampleは実際の問題ページを見てください

2369. Check if There is a Valid Partition For The Array 問題ページ

2369. Check if There is a Valid Partition For The Array

[leetcode] 2369. Check if There is a Valid Partition For The Array

my code is not good(worng answer)

function validPartition(nums: number[]): boolean {
        function fuc(nums, i){
        return nums[i] && nums[i+1] -1 && nums[i+2] - 2
    }
    for (let index = 0; index < nums.length; index++) {
        if(nums[index] === nums[index+1]){
            if(fuc(nums, index+2)) return true   
            if(nums[index] === nums[index+2]){
                return nums[index+3] === nums[index+4]
            }

        }
        if(fuc(nums, index)){
            return nums[index+3] === nums[index+4]
        }
    }
    return false
};

撃沈しました

[leetcode] 2369. Check if There is a Valid Partition For The Array。discussの中の一つの解答例

数ある中からJavaScriptのもので、理解しやすい解説をピックアップしました。
discussから見ればさらにもっと違う方法で真似したくなるものがあるかもしれないですね

JavaScriptでfilterされている、discussはこちらから

2369. Check if There is a Valid Partition For The Array

3つの条件がある

  1. 連続する同じ数字が2つあるか
  2. 連続する同じ数字が3つあるか
  3. インクリメントしていく数字が3つ続くか

1があったら、2,3を調査する helperを呼ぶ。indexを2つ先にして渡し、trueならメモ化したのち処理を戻す
2があったら、インデックスを3つ先にして渡す
trueならメモ化したのち処理を戻す
3がtrueならインデックスを3つ先にしてわたす

   let dp = Array(nums.length).fill(-1) // [-1, -1, -1, -1, -1] メモ化の為
    function helper(nums, i) {
        if (i === nums.length) return true;
        if (dp[i] !== -1) { // あれば計算しないで返す
            return dp[i];
        }
        // 1
        if (i + 1 < nums.length && nums[i] == nums[i + 1]) {
            if (helper(nums, i + 2)) {
                dp[i] = true;
                return true;
            }
        }
        // 2
        if (i + 2 < nums.length && nums[i + 2] == nums[i] && nums[i+1]==nums[i]) {
            if (helper(nums, i + 3)) {
                dp[i] = true;
                return true;
            }
        }
        // 3
        if (nums[i + 1] == nums[i] + 1 && nums[i + 2] == nums[i] + 2) {
            if (helper(nums, i + 3)) {
                dp[i] = true;
                return true;
            }
        }
        return dp[i] = false;
    }
    return helper(nums, 0)

[leetcode] 2369. Check if There is a Valid Partition For The Arrayをやってみて感想

  • 再帰だけやったのではパフォーマンスが悪いのでメモ化すること

カテゴリー leetCode