题解 | #两数之和#
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
public class Solution {
public int[] twoSum (int[] numbers, int target) {
int[] res = new int[0];
//创建哈希表,两元组分别表示值、下标
HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
//在哈希表中查找target-numbers[i]
for(int i = 0; i < numbers.length; i++){
int temp = target - numbers[i];
//若是没找到,将此信息计入哈希表
if(!hash.containsKey(temp)){
hash.put(numbers[i], i);
}
//否则返回两个下标+1
else
return new int[] {hash.get(temp) + 1, i + 1};
}
return res; }
}