1. 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
Given a sorted array of integers numbers, find out two of the numbers in which the sum can be equal to target. Output their ordinal number in the array.
2. Ideas
Look at the other problem solving report, some of it is too complicated to write. The general first idea is that two for loops, this idea is not good, time complexity is $o (n^2) $, the array is slightly larger when the time out. The second more general idea is to find TARGET/2, with this as the dividing line, forward and backward judgment, but this method is not the best. The third idea is to say next, the complexity is $o (n) $ The idea-starting at both ends, recorded as I and J:
(1) If the result of numbers[i]+numbers[j] is greater than target, the J is shrunk, because if I is added again, then the numbers[i]+numbers[j] result will be greater.
(2) If the result of Numbers[i]+numbers[j] is less than target, increase the I, because if J is reduced again, then numbers[i]+numbers[j] results will be smaller.
3. Code
Class Solution{public: vector<int> twosum (vector<int>& numbers, int target) { int i=0,j= Numbers.size ()-1; while (i<j) { if (numbers[i]+numbers[j]==target) return {i+1,j+1}; else if (numbers[i]+numbers[j]>target) j--; else if (numbers[i]+numbers[j]<target) i++; } Return {0,0};} ;
LeetCode-167. Double Sum Ii-input Array is sorted-o (n)-(c + +)-Problem Solving report