The main idea is that there is only one solution (pair of of target sum).
If you start from left and right and check the sum, eventually you will stumble across the pairs.
Updating pointers is easy because array is sorted. Updating left/right increases/decreases sum as array is sorted.
The increase/decreases will never overshoot the solution because array is sorted.
// Runtime: 1 ms, faster than 58.31% of Java online submissions for Two Sum II - Input array is sorted.// Memory Usage: 41.4 MB, less than 28.48% of Java online submissions for Two Sum II - Input array is sorted.importjava.lang.*;classSolution{publicint[]twoSum(int[]numbers,inttarget){int[]pairs={0,0};intl=0;intr=numbers.length-1;while(l<r){intsum=numbers[l]+numbers[r];if(sum==target){pairs[0]=l+1;// 1-indexedpairs[1]=r+1;// 1-indexedreturnpairs;}// update ruleif(sum<target){l++;}elseif(sum>target){r--;}}returnpairs;}}