1 和为s的两个数,利用begin,end两个位置标志和为s前后两个元素,当和大于s,end前移,和小于s,begin后移
vector<int> FindNumbersWithSum(vector<int> array,int sum) { 2 vector<int>res; 3 if(array.size()==0) 4 return res; 5 bool found=false; 6 int cursum=0; 7 int begin=0; 8 int end=array.size()-1; 9 while(begin<end) 10 { 11 cursum=array[begin]+array[end]; 12 if(cursum==sum) 13 { 14 res.push_back(array[begin]); 15 res.push_back(array[end]); 16 found=true; 17 break; 18 } 19 else if(cursum<sum) 20 begin++; 21 else 22 end--; 23 24 25 } 26 return res; 27 }
和为s的连续正整数序列,让small初始为1,big初始为2,cursum初始为small+big,当smal小于(s+1)/2时,big递增,cursum+big;当cursum比当前s大时,cur-small,small前移,如果cursum和s相等,加入结果序列
1 void addtoresult(int small,int big,vector<int>&num,vector<vector<int>>&res) 2 { 3 num.clear();//每次记录新的序列前应该清除旧的序列 4 for(int i=small;i<=big;i++) 5 { 6 num.push_back(i); 7 } 8 res.push_back(num); 9 } 10 vector<vector<int> > FindContinuousSequence(int sum) { 11 vector<vector<int>>res; 12 vector<int>num; 13 if(sum==1 ||sum==2) 14 { 15 return res; 16 } 17 int small=1; 18 int big=2; 19 int middle=(1+sum)/2; 20 int cursum=small+big; 21 while(small<middle) 22 { 23 if(cursum==sum) 24 { 25 addtoresult(small,big,num,res); 26 } 27 while(cursum>sum&&small<middle) 28 { 29 cursum-=small; 30 small++; 31 if(cursum==sum) 32 addtoresult(small,big,num,res); 33 } 34 big++; 35 cursum+=big; 36 } 37 return res; 38 }