#include <iostream>
#include <vector>
using namespace std;
int FindMinIndex(vector<int>data)
{
if(data.size()<1){
return -1;
}
if(data.size()==1)
return 0;
int index = 0;
int min = data[0];
for(int i=1; i<data.size();i++){
if(min>data[i]){
min = data[i];
index = i;
}
}
return index;
}
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
int len = array.size();
vector<int> res,tmparr,sumarr;
if(len <=0)
return res;
int start = 0;
int end = len -1;
while(start<end){
if(array[start]+array[end]==sum){
tmparr.push_back(array[start]);
tmparr.push_back(array[end]);
int pro = array[start]*array[end];
sumarr.push_back(pro);
//被自己蠢哭了,这里本来少了下一句,导致内存蹭蹭蹭上涨,以至于超内存
//其实这个题,按照该思路,只需要找到第一组和为相对应的两个数就可以
//因为第一次寻找到的两数之积,是最小的。。。。
//自作多情的要找一个方法来找,然后,然后,就出错了。。。虽然找到了错误,但是果然常犯的毛病
start++;
}
else if(array[start]+array[end]>sum&&(start<end))
end--;
else if(array[start]+array[end]<sum&&(start<end))
start++;
}
int index = FindMinIndex(sumarr);
if(index>-1){
if(2*index+1<tmparr.size()){
res.push_back(tmparr[2*index]);
res.push_back(tmparr[2*index+1]);
}
}
return res;
//return tmparr;
}
int main(){
vector<int> data={1,2,3,4,5,6,7,8,9,10};
vector<int> twonumber= FindNumbersWithSum(data,10);
for(int i = 0; i<twonumber.size();i++){
cout<<twonumber[i]<<endl;
}
/**int res = FindMaxIndex(data);
cout<<res<<endl;
cout<<data[2*res]<<endl;
cout<<data[2*res+1]<<endl;*/
return 0;
}
我是分界线,下一题,和为S的正数序列
vector<vector<int> > FindContinuousSequence(int sum) {
int small = 1;
int big = 2;
vector<vector<int>> xulie;
if(sum<=2)
return xulie;
int middle = (sum+1)/2;
int currsum = small+big;
int i = 0;
while(small<middle){
if(currsum==sum){
vector<int> arr;
for(int tmp = small; tmp<=big;tmp++){
arr.push_back(tmp);
}
xulie.push_back(arr);
}
while(currsum > sum&&small<middle){
currsum-=small;
small++;
if(currsum==sum){
vector<int> arr;
for(int tmp = small;tmp<=big;tmp++)
arr.push_back(tmp);
xulie.push_back(arr);
}
}
big++;
currsum+=big;
}
return xulie;
}