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
的数的数组下标(题目假设只有一个解,也就是数组每个元素唯一)
主要是利用的hash的思想,保存下标位置,查找时间为O(1),而不用每次去遍历数组。
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[]{0,0};//返回值
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0;i<nums.length;++i){
if(map.containsKey(target - nums[i])){ //如果之前的数中有和num[i]相加为target的数
//返回结果
result[0] = map.get(target-nums[i]);
result[1] = i;
break;
}else{
//把位置记录到map中
map.put(nums[i], i);
}
}
//System.out.println(result[0]+" "+result[1]);
return result;
}
}