かずとよのアウトプット日記

開発エンジニアを目指しています。

leetcodeを始めました。

スキルテストで、leetcodeから出題されることがわかった為、登録をして初めてみました。

SNSサインアップができたので、とりあえず済ませ、早速・・・

 

全部、英語。

英語です。正直全然わからないものの、なんとか問題ページに辿り着き、とりあえず一問解いてみようと、難易度easyの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].

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.

 

 

うん、わからん。

 

翻訳サイトを駆使して、問題文を読み解きます。

 

・・・おそらくですが。

【仮引数numsには数値がいくつか入った配列を、targetには数値ひとつを、実引数として渡します。

numsの中のどことどこの数値を足せばtargetになるかを出力させる。

当てはまるのは1パターンですよ。】

的な意味かな?おそらく。

 

早速、試行錯誤しながら解いてみて、導き出せた僕の回答は以下。(1時間ぐらいかかった・・・)

 

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}

def two_sum(nums, target)
  nums.each_with_index do |i, idx|
           # 配列numsを繰り返し処理。オプションでインデックスも取得する
    x = target - i
           # 変数xにtargetからiを引いて、あと数字がいくつ残るかを代入
    if nums.include?(x) && nums.index(x) != idx
           # 配列内にxがあって、且つ、xがidxと同じでないならば
      y = nums.index(i)
      z = nums.rindex(x)
      return [y, z]
    end
  end
end

 

これで一応クリアできた・・・

めちゃくちゃ難しかったです。

 

*今回の学び:

  • each_with_indexを使うと、繰り返し処理の際にその処理をしている要素の順番も取得できる。
  • 配列.index(要素)で、その要素の場所を頭から探し、最初に当てはまった場所の順番を取得できる
  • 配列.rindex(要素)は、上記の逆から探してくれる版。
  • 2つの数字の和を探すときは、差を見ればすぐに探し出せる。