LoginSignup
1
0

More than 3 years have passed since last update.

LeetCodeでブートキャンプ①

Last updated at Posted at 2021-04-07

この記事について

考える力を付けたい。
そのために最近知ったLeetCodeでコーディングの練習を始めました。
自分が辿った思考方法を文章化していきたいと思います。

ついでに英語の勉強もしたい!!!!

LeetCodeについて説明されている記事

補足

僕は業務経験は半年もない、ペーペーのエンジニアです。
優しくて、暖かすぎて熱くなるくらいの目でこの記事を読んでください。

問題(Two Sum)

Given an array of integers nums and an integer target, 
return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, 
and you may not use the same element twice.

You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

和訳(なんとなく)

整数が入った配列と、整数のtargetが与えるで。
足された合計がtargetになるindexを返してな。

同じ要素を2回使ったらダメよ!!
答えはどんな順番になっても大丈夫やで。

最終的な僕の回答

Input: nums = [2,7,11,15], target = 9


def two_sum(nums, target)
    output = []
    nums.each_with_index do |num1, i1|
        nums.each_with_index do |num2, i2|
            next if i1 == i2 || i1 > i2
            if num1 + num2 == target
                output << i1
                output << i2
            end
        end
    end

    output
end

Output: [0,1]

思考軌跡

其の1 each使う

配列を2回、回してそれぞれの要素足すようにしたらいいか。

Input: nums = [2,7,11,15], target = 9


def two_sum(nums, target)
    output = []
    nums.each do |num1|
        nums.each do |num2|
        end
        end
    end

    output
end

これやと、どのindex同士が足されたか分からんなぁ。。。

其の2 each_with_index使う

each_with_indexで要素番号分かるようになったし、これでoutputに値を入れていけるわ!!!

Input: nums = [2,7,11,15], target = 9

def two_sum(nums, target)
    output = []
    nums.each_with_index do |num1, i1|
        nums.each_with_index do |num2, i2|
            next if i1 == i2
            if num1 + num2 == target
                output << i1
                output << i2
            end
        end
    end

    output
end


Output: [0,1,1,0]

返ってきた値が[0,1,1,0]になってる。
1度足された同士の要素は計算しいひんようにせなあかんな。

其の3 next ifの条件を変える(完成!!!!)

i1 > i2、で最初のeachのindexが、2つ目のeachのindexよりも大きい場合はnextで次の繰り返しに行くようにした。

Input: nums = [2,7,11,15], target = 9


def two_sum(nums, target)
    output = []
    nums.each_with_index do |num1, i1|
        nums.each_with_index do |num2, i2|
            next if i1 == i2 || i1 > i2
            if num1 + num2 == target
                output << i1
                output << i2
            end
        end
    end

    output
end


Output: [0,1]  #できた!!!!

感想

バリバリのエンジニアの方やったらもっとシンプルに記述できるんでしょうな。。。
簡単とは言え、ヒントも見ずに問題を解けるのは嬉しい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0