您的位置:首页 > 其它

Two Sum(找出数组中两个和等于指定数字的元素)

2016-01-21 21:21 357 查看
英文:

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.

中文:

给出一组整数,找出其中两个元素,它们的和为我们指定的某个数字,实现函数返回这两个元素从1开始计算的位置,返回值要求第一个数字小于第二个数字。假设给出的数组只有一组解。

例如:给出数组{2, 7, 11, 15},指定的数字是9,则应该返回1和2,因为第一个数字2加上第二个数字7的和是9

从前向后考察数组中各个元素,每查到一个元素,如果HashMap中没有以该元素为键的项,便在HashMap中添加一项,添加的项以指定数字与该元素的差为键,以该数字下标为值;如果HashMap有以该元素为键的项,则将当前位置的下标和HashMap中对应项的值(也是之前存进去的下标),加一后返回
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: