leetcode twopointer: two numbers whose sum is s

THE

problem

Insert picture description here

content

Ideas

  1. The increasing sequence contains some information. The complexity of the violence method for this question is N^2. Another method is to fix the left side and move the right side according to the target. But this is not the traditional method of double pointers. We need to pay attention to the problem that the implicit condition for the smallest printing product is the smallest set on the left. Therefore, the left and right pointer switching method similar to binary search is adopted.
    coding
  • define ans vector ;
  • define left right
  • while()
    • sum = a[left] + a[right-1];
    • if sum== return
    • if sum> right --;
    • if < left ++;
  • return ans;

Summary and reflection

  1. Vectors need to be proficient in using APIs, and they cannot create or insert them.

Code

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

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114005592