利用hashmap搜索。hash map的key是数组中的数字,value是这个数字的index。找到对应的数字后输出其index。
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> check = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(check.containsKey(target-nums[i])){
return new int[]{check.get(target-nums[i]),i+1};
}
else
check.put(nums[i], i+1);
}
return null;
}
}
Fight On!