[Algorithm Topic Breakthrough] Double pointers - two numbers whose sum is s (6)

Table of contents 

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

Question link: Sword refers to Offer 57. Two numbers whose sum is s - Leetcode

 This question only has one sentence, but there is information that can be extracted.

The most important thing is the sentence at the beginning, "increasing sequence"

Then just find two numbers in the array whose sum is s (and it can be any pair)

2. Algorithm principle

This question is very simple. If you use brute force enumeration and directly use two layers of for loops to solve it,

However, if you use a brute force solution, you will not take advantage of the fact that it is an ordered sequence.

When we see order, we usually think of using dichotomy, but dichotomy is more difficult to write.

So I plan to use monotonicity and use double pointers to solve this problem:

We use the left pointer to point to the left and the right pointer to point to the right, and then start the operation:

sum is the value of left + right,

If: sum < target, let the left pointer move right to find a larger number

If: sum > target, move the right pointer left to find a smaller number

If: sum == target, just return the result.

3. Code writing

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

Write at the end:

The above is the content of this article, thank you for reading.

If you feel that you have gained something, you can give the blogger a like .

If there are omissions or mistakes in the content of the article, please private message the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131610173