您的位置:首页 > 编程语言 > Java开发

leetcode Two sum

2015-06-22 00:00 453 查看
摘要: 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 an...

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+1 ;

result[1] = i+1;

break;

} else {

map.put(target - numbers[i], i);

}

}

return result;

}

}

此代码比较高明的地方在于使用map的key存储我们需要的数值,而他的下标存在value中。

map.containsKey(numbers[i]) 用于判断之前存储的key里有没有值为target-numbers[i],如果有

则找到。

但是上述代码有个缺陷,无法找到所有可能的组合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode