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: Since this array is sorted, we can use two pointers (left, right) to point to the start and the end of the array. If the sum is bigger than target, make the sum smaller by decrease the right pointer, otherwise increase the left pointer to make the sum bigger. The loop ends when the sum is equal to the target. Take care the output index is the original index+1.
Time: O(n) Space: O(1)
Code:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int left=0;
int right=numbers.length-1;
int[] result=new int[2];
while(left<right)
{
int sum=numbers[left]+numbers[right];
if(sum==target)
{
result[0]=left+1;
result[1]=right+1;
return result;
}
if(sum<target)
left++;
else
right--;
}
return result;
}
}
No comments:
Post a Comment