LoginSignup
1
1

More than 3 years have passed since last update.

RubyでLeetCodeを解いてみた Two Sum

Last updated at Posted at 2020-01-17

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

意外とむずいよね

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
    nums.each_with_index do |num, idx|
        x = target - num
        if num == x
            y = nums.rindex(x)
            next if idx == y
            return [idx, y]
        end
        y = nums.index(x)
        next if y == nil
        return [idx, y]
    end
end

一応通りましたが、酷いコード😇

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