1.Brute Force
public int[] twoSum(int[] nums,int target){
int[] res = new int[]{};
for(int i = 0;i < nums.length;i++){
for(int j = i+1;j < nums.length;j++){
if(nums[i] + nums[j] == target){
res = new int[] {i,j};
}
}
}
return res;
}
2.HashMap
public int[] twoSum(int[] nums,int target){
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
hash.put(nums[i],i);
}
for(int i = 0; i < nums.length; i++){
int left = target - nums[i];
if(hash.containsKey(left) && hash.get(left) != i){
return new int[]{i,hash.get(left)};
}
}
return new int[]{};
}