20.4.10 Sum of Two Numbers II-Simple input to ordered array

topic

Given an ordered array that has been sorted in ascending order, find two numbers so that the sum of them equals the target number.
The function should return these two index values ​​index1 and index2, where index1 must be less than index2.

Explanation: The
returned subscript values ​​(index1 and index2) do not start from zero.
You can assume that each input only corresponds to a unique answer, and you cannot reuse the same element.

Example:
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 equals the target number 9. Therefore index1 = 1, index2 = 2.

Problem-solving ideas

  1. Because it is ordered, you can use the dichotomy
  2. Specify a number as index1, then search for index2 using the dichotomy after this number. If it is not found, change to index1 and loop until it finds the result.

Code ideas

  1. Loop through the entire array, set the current traversal number as index1, and use the dichotomy to find index2 after the number of index1;
  2. If the current dichotomy cannot find a suitable index2, update index1;
  3. If index2 is found, the flag becomes true, and the while and for loops jump out, and the result is obtained.

Code

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;
        if(numbers.size() == 0) return result;

        int index1;
        int index2;
        for(int i = 0; i < numbers.size() - 1; i++){
            index1 = i;
            int begin = i + 1;
            int end = numbers.size() - 1;
            bool flag = false;
            while(begin <= end){
                int mid = (begin + end) / 2;
                if(numbers[index1] + numbers[mid] == target){
                    flag = true;
                    index2 = mid;
                    break;
                }
                if(numbers[index1] + numbers[mid] > target) end = mid - 1;
                if(numbers[index1] + numbers[mid] < target) begin = mid + 1;
            } 
            if(flag) break;
        }
        result.push_back(index1 + 1);
        result.push_back(index2 + 1);

        return result;
    }
};

Guess you like

Origin www.cnblogs.com/wasi-991017/p/12676083.html