Leetcode 1 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

使用Hash存储每个值所对应的数组下标。

h = { :a[index1] => index1, :a[index2] => index2, ... }

需要两个值加起来等于Sum,只需要检查是否在Hash中存在Sum减去第一个值后第二个值的key(第一个值通过遍历数组得到),并且这两个值不是同一个数(对应相等的数组下标)。

需要注意最后求的两数是在数列中的顺序,应为数组下标+1。

def two_sum(num, target)
    h = {}
    num.length.times {|i| h[num[i]] = i}
    num.length.times {|i| return i+1, h[target-num[i]]+1 if h[target-num[i]] and h[target-num[i]] > i}
end

 

posted @ 2015-06-11 15:37  lilixu  阅读(124)  评论(0编辑  收藏  举报