Question
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].
问题解析:
从给定数组中,找到两个和为目标数值的两个元素,返回元素在数组中的索引值。
Answer
Solution 1:
排除循环嵌套的暴力搜索法,能想到的一种解法就是利用Map去实现。
- 观察题目可知,如题例子:9-2=7,所以我们可以通过判断
target - nums[i]
的结果是否已经存在于Map中,就可以一次遍历找到两个对应的目标值; - 如果结果不存在Map中,则保存相应的
nums[i]
,一旦找到则返回结果; - 其中,Map中保存的值对是目标元素和其对应的索引。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i<nums.length; i++){
if (map.containsKey(target - nums[i])){
result[0] = map.get(target - nums[i]);
result[1] = i;
return result;
}
map.put(nums[i], i);
}
return result;
}
}
- Runtime:7 ms
- Beats 91.39 % of java submissions
- 时间复杂度:O(n),空间复杂度:O(n)