2023-07-08 LeetCode Daily Question (Sum of Two Numbers II - Input Ordered Array)

2023-07-08 one question per day

1. Topic number

167. 两数之和 II - 输入有序数组

2. Topic link

Click to jump to the topic location

3. Topic description

You are given an integer array numbers whose subscript starts from 1. The array has been arranged in non-decreasing order . Please find two numbers from the array that satisfy the sum of the sum to be equal to the target number target. If these two numbers are numbers[index1] and numbers[index2] respectively, then 1 <= index1 < index2 <= numbers.length.

Returns the indices index1 and index2 of these two integers as an array of integers of length 2 [index1, index2].

You can assume that each input corresponds to a unique answer , and you cannot reuse the same elements.

The solution you design must use only a constant amount of extra space.

hint:

  • 2 <= numbers.length <= 3 * 104
  • -1000 <= numbers[i] <= 1000
  • numbers in non-decreasing order
  • -1000 <= target <= 1000
  • only one valid answer exists

4. Problem solving code

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
    
    
        vector<int> res;
        int left = 0;
        int right = numbers.size()-1;
        while(left < right){
    
    
            if(numbers[left] + numbers[right] > target){
    
    
                right--;
            } else if(numbers[left] + numbers[right] == target){
    
    
                res = {
    
    left + 1, right + 1};
                break;
            } else{
    
    
                left++;
            }
        }
    return res;
    }
};

Five, problem-solving ideas

(1) Use double pointers to solve the problem.

(2) Record the length of the entire array as n, the left pointer left initially points to the place where the subscript is 0 in the array, and the right pointer right points to the place where the subscript is n-1 in the array. If nums[left] + nums[right] is equal to target, it meets the requirements. If nums[left] + nums[right] is less than target, the value should be increased, then left should be +1, if nums[left] + nums[right] ] is greater than target, the value should be reduced, and right should be reduced by 1.

(3) Finally, don't forget that the subscript of the result array should be the subscript of the original array + 1.

Guess you like

Origin blog.csdn.net/qq_56086076/article/details/131607369