您的位置:首页 > 其它

Leetcode 1 Two Sum

2015-06-11 15:37 399 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: