Given an array of integers that's already sorted in ascending order, find, numbers such, they add up to a Specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution and you may not use the same element TWIC E.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Title Tags: Array, pointers
The topic gives us an array, and a target, array is ascending, let's find two numbers and equals target. This is to return their index, but starting from 1.
Using the pointers, a left = 0, a right = Numbers.length-1, because the array is ascending, so when the left number + the number is greater than the target, it is too large to be Smaller numbers, so take the right--to get a smaller number;
When the left number + right number is less than target, the sum is too small, need a larger number, so the left++ to get a larger number;
When the left number + right number equals target, the index + 1 is returned directly.
Java Solution:
Runtime beats 44.34%
Completion Date: 04/06/2017
Key words: Array, pointers
Key points: Learn how two numbers and compare to target two pointers how to move, built in the case of incrementing an array
1 Public classSolution2 {3 Public int[] Twosum (int[] numbers,inttarget)4 {5 intleft = 0, right = numbers.length-1;6 intRes[] =New int[2];7 8 while(Left <Right )9 {Ten //Find Numbers One if((Numbers[left] + numbers[right]) = =target) A { -Res[0] = left + 1; -Res[1] = right + 1; the Break; - } - Else if((Numbers[left] + numbers[right]) > Target)//if greater, right moves to left 1 place -right--; + Else //if less, left moves to right 1 place -left++; + A } at - returnRes; - } -}
Resources:
Http://www.cnblogs.com/ganganloveu/p/4198968.html
Leetcode algorithm topic List- leetcode algorithms Questions list
Leetcode 167. Two Sum ii-input array is sorted (two sum of numbers-input is ordered array)