码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 1 Two Sum

时间:2015-06-11 16:12:11      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Leetcode 1 Two Sum

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4569255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!