The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Idea: Scan the array from left to right. Use a hash map (from value to its index) to remember the values visited. If the "target-current" already exists in the hash map, return the result.
Time: O(n) Space: O(n)
Code:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer,Integer> valToPos=new HashMap<Integer,Integer>();
int[] result=new int[2];
for(int i=0;i<numbers.length;i++)
{
int needed=target-numbers[i];
if(valToPos.containsKey(needed))
{
result[0]=valToPos.get(needed)+1;
result[1]=i+1;
return result;
}
else
{
valToPos.put(numbers[i],i);
}
}
return result;
}
}
No comments:
Post a Comment