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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
题意:给你一个int类型的数组(没有排序的),从里面选出两个数,让他们的和等于target的值,并返回原数组中,这两个数的下标。
使用hash map 可以省去查找的算法。
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int[] restule=new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int a=map.get(nums[i]);
restule[0] = a;
restule[1] = i;
}else{
map.put(target - nums[i], i);
}
}
return restule;
}
代码:使用target-mus[i]做键,下标做值是代码的巧妙之处。