0
0

More than 3 years have passed since last update.

Two Sum 〜leetcode〜

Last updated at Posted at 2021-03-08

〜問題文〜

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].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]


Constraints:

2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

引用元: https://leetcode.com/problems/two-sum/
  

簡単に要約すると、

「与えられた配列(nums)内の数字同士で、足し合わせると、targetになる配列要素の添字(インデックス)を、2つ、配列として出力するようなメソッドを作りなさい。」

だそうです。  

〜回答例〜


def two_sum(nums, target)
    search = Hash.new
    nums.each_with_index do |item,index|
        i = search[target-item]
        return [i+1, index+1] if i != nil
        search[item] = index
    end
end

回答例引用元(一部改変):
https://leetcode.com/problems/two-sum/discuss/55/Accepted-ruby-solution

以下、上記回答の分解分析

1. メソッドの定義


def two_sum(nums, target)

        〜省略〜

end

「two_sum」というメソッドで第一仮引数=「nums」と第二仮引数= 「target」と定義する。

2. 変数searchに代入


         〜省略〜

    search = Hash.new

         〜省略〜

変数「search」に対して、「Hash.new」を代入する。

Hash.newについては以下を参考にする。

参考:https://docs.ruby-lang.org/ja/latest/method/Hash/s/new.html



    nums.each_with_index do |item,index|

          〜省略〜

    end

「each_with_index」メソッド。
要素とその添字(インデックス)をブロックに渡して繰り返すメソッド。

参考:https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/each_with_index.html

今回場合、ブロック変数の「index」部分に、添字(インデックス)が入ってくる。
また、添字は0から開始する。

3. 以下、繰り返し部分



 i = search[target-item]

変数「 i 」に「search(=Hash.new)」を代入する。
「search」の添字の指定は、「target(=本メソッドの仮引数)」-「item(=numsの各要素)」で行う。



  return [i+1, index+1] if i != nil


「return ~ if」の書き方は以下を参考にした。
参考:https://qiita.com/okhrt/items/3e98ba496bcf8c50ac64

つまり「return 処理 if 条件」。

「i (=search(=Hash.new))がnil(空)でなければ、 「i+1」 と 「index(=添字)+1」を配列で返しなさい。」という意味。

全体の最終的ゴールの出力はこの行。


 search[item] = index

継続する場合はこちらに続く。
「search(=Hash.new)」の添え時として、「item(=numsの各要素)」を指定してあげた数値は、indexに代入される。

処理後再びループへ。

0
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
0
0