您的位置:首页 > 其它

Two Sum(easy)

2016-06-07 09:32 232 查看
题目

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.

Example:

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

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


题意

分析

首先,不能对该数组作任何预处理。因为要求返回是原始数组的下标,如果对数组进行了排序,那么下标就会乱。

(如果是有序数组,可以用双指针来做,参见Two Sum II - Input array is sorted

很容易想到用<value, index>的映射表。

遍历numbers,在映射表中寻找target-numbers[i].

若找到则结束,返回存储的下标+1和当前下标+1. (注意题目中规定,以1作为起始下标)

若找不到则将<numbers[i], i>加入映射表。

O(n)。哈希表。将每个数字放在map中,历遍数组,如果出现和数组中的某一个值相加为target的时候,break。这个方法同样适用于多组解的情况。

实现

public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];

for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index ;
result[1] = i;
break;
} else {
map.put(target - numbers[i], i);
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: