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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
分析:题目的要求是给出一个数组以及一个数target,找到该数组中哪两个数的和是target,返回一个存储这两个数索引的数组。
target - nums[i]
是否在map中,如果不在则将该数以及对象索引加入map,否则就找到了这两个索引了。class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans = {-1, -1};
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])){
ans[0] = map.get(target - nums[i]);
ans[1] = i;
}else {
map.put(nums[i], i);
}
}
return ans;
}
}
原文:https://www.cnblogs.com/zhuobo/p/10749960.html