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].
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap<Integer,Integer> hashmap = new HashMap<>();
//List arrayList = Arrays.asList(nums);
HashMap<Integer,Integer> index = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(index.get(nums[i])==null)
index.put(nums[i],i);
else if(2*nums[i]==target){
result[0]=i;
result[1]=index.get(nums[i]);
return result;
}
}
for(int i=0;i<nums.length;i++){
//if(hashmap.get(target-nums[i])==null)
hashmap.put(target-nums[i],nums[i]);
}
//Set set = hashmap.keySet();
for(int i=0;i<nums.length;i++){
if(hashmap.get(nums[i])!=null){
if(index.get(nums[i])!=index.get(target-nums[i])){
result[0]=index.get(nums[i]);
result[1]=index.get(target-nums[i]);
}
}
}
return result;
}
}
兩個特殊的地方:
1.
target=6,int[]{3,3}
2.
target=28,int[]{1,27,14}
剛好有目標值的一半