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

[leetcode]問題解答と解説。15. 3Sum [JavaScript]

[leetcode]問題解答と解説。15. 3Sum [JavaScript]

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

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

では今日のleetCode。
【15. 3Sum】の解決策と方法。自分がまず挑戦して
やったことをさらけ出します。

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

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

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

[leetcode] 15. 3Sum ルール

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

要は、要素3つ足して0になるペアを全て配列で格納しろというもの
回答は3つの重複している要素を含んではいけない

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

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

[leetcode] 15. 3Sum 問題ページ

15. 3Sum

[leetcode] 15. 3Sum

my code is not good(time out)

var threeSum = function(nums) {
    nums.sort((a, b) => a -b)
    let first = 0
    let mid = Math.floor(nums.length /2)
    let therd = nums.length -1
    if((nums[first] + nums[mid] + nums[therd]) === 0) return [0, 0, 0]
    while((first !== mid) && therd !== mid){
        if(nums[first] + nums[mid] >  nums[therd]){

        }

    }
};

時間切れ。
やりたかったことは、

[leetcode] 15. 3Sum。discussの中の一つの解答例

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

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

気に入った解答1

[leetcode] 15. 3Sum をやってみて感想

カテゴリー leetCode