The original title link is here: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Topic:
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.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Exercises
Says the pointer moves from both ends to the middle. Similar to the Sum of a.
Time Complexity:o (n). Space:o (1).
AC Java:
1 Public classSolution {2 Public int[] Twosum (int[] numbers,inttarget) {3 int[] res =New int[]{-1,-1};4 if(Numbers = =NULL|| Numbers.length < 2){5 returnRes;6 }7 intL = 0;8 intr = Numbers.length-1;9 while(l<R) {Ten if(Numbers[l] + Numbers[r] <target) { Onel++; A}Else if(Numbers[l] + numbers[r] >target) { -r--; -}Else{ theRes[0] = l+1; -RES[1] = r+1; - Break; - } + } - returnRes; + } A}
Leetcode the Sum ii-input array is sorted