LeetCode: two sum
最近研究以外であんまりコードを書いていなかったので会社に入ってから使うであろうRubyでLeetCodeを解いてリハビリをしていこうと思う
1日1問を目標に解く&解説していけばいきたい
今日ははじめにTwo Sumを解いた
問題
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
整数の配列を指定すると、特定のターゲットに加算されるように2つの数値のインデックスを返します。
You may assume that each input would have exactly one solution, and you may not use the same element twice.
各入力には1つの解しか存在しないと想定し、同じ要素を2回使用することはできません。
俺の回答
# @param {Integer[]} nums # @param {Integer} target # @return {Integer[]} def two_sum(nums, target) hash = {} for i in 0..nums.size - 1 do hash[nums[i]] = i; end for i in 0..nums.size - 1 do value = target - nums[i] if hash.has_key?(value) && hash[value] != i return [i, hash[value]] end end end
解説
1問目だから結構簡単だった
ハッシュテーブルに各要素の値とインデックスを格納して、その後にtargetから各要素の値を引いた値がハッシュテーブルのkeyに存在するか探索してオワオワリ
最初「You may assume that each input would have exactly one solution, and you may not use the same element twice. 」の文を読み飛ばしてたせいで、なんでWAになるんや穀すぞと思っていたけど俺が悪かっただけでした