Hashmap
One solution is to use hashmap to quickly check whether we have seen (target - nums[i])
- if so, we return a new array with the index of (target - nums[i]) and nums[i]. (Be aware that, index of (target- nums[i]) must be smaller than nums[i], since we have sort the array, smaller element should be put first.)
- if not, put current element into the map
- stop when current element is larger than target
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
return new int[] {map.get(target-nums[i]),i+1};
}
else if(nums[i]>target){
break;
}
else{
map.put(nums[i],i+1);
}
}
return null;
}
}
Two pointer
We can use two pointer, one point to the start of array, one point to the end of array. Then, since there is only one solution and the array has already been sorted. We know
- if nums[i]+nums[j] < target, that means nums[i] is too small, i++
- if nums[i] + nums[j] > target, that means nums[j] is too big, j–
- if equal, return
- if i>j, stop
class Solution {
public int[] twoSum(int[] nums, int target) {
int i = 0 , j = nums.length-1;
while(i<j){
while(nums[i]+nums[j]<target) i++;
while(nums[i]+nums[j]>target) j--;
if(nums[i]+nums[j]==target){
return new int[] {i+1,j+1};
}
}
return null;
}
}