两次遍历
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> numsMap = new HashMap<Integer,Integer>();
int length = nums.length;
for(int i=0;i<length;i++){
numsMap.put(nums[i],i);
}
for(int i=0;i<length;i++){
int another = target - nums[i];
if(numsMap.containsKey(another) && i != numsMap.get(another)){
return new int[]{i,numsMap.get(another)};
}
}
throw new IllegalArgumentException ("无解");
}
一次遍历
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> numsMap = new HashMap<Integer,Integer>();
int length = nums.length;
for(int i=0;i<length;i++){
int a = nums[i];
int b = target - a;
if(numsMap.containsKey(b)){
return new int[]{i,numsMap.get(b)};
}
numsMap.put(nums[i],i);
}
throw new IllegalArgumentException ("无解");
}