题目如下:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2。
大意:
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。
纯粹为了写着好玩。(#^.^#)
#include "cctype"
#include "iostream"
#include<math.h>
#include <ctime>
#include "afxtempl.h"
using namespace std;
#define random(a,b) (rand()%(b-a+1)+a)
#define MAX_INDEX 20 //定义数组个数
class node
{
public:
int this_index;
int next_index;
int two_sum;
};
CArray<node,node> result_group;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int *original;
original=(int*)malloc(MAX_INDEX*sizeof(int));
//产生原始数组
for (int m=0;m<MAX_INDEX;m++)
{
int i=random(1,5);
if (m==0)
{
original[m]=i;
}
else
original[m]=i+original[m-1];
char msgbuf[100];
sprintf(msgbuf," %d ",original[m]);
OutputDebugStringA(msgbuf);
}
for (int m=0;m<MAX_INDEX;m++)
{
cout<<" "<<original[m];
}
for(int i=0;i<MAX_INDEX;i++)
{
for (int m=0;m<MAX_INDEX;m++)
{
if (i<m)
{
node tmp;
tmp.this_index=i;
tmp.next_index=m;
tmp.two_sum=original[i]+original[m];
result_group.Add(tmp);
}
}
}
cout<<"是否继续(输入#结束)"<<endl;
char con;
cin>>con;
while(con!='#')
{
cout<<"输入目标数字"<<endl;
int target;
cin>>target;
char msgbuf[100];
sprintf(msgbuf,"\n target is %d ",target);
OutputDebugStringA(msgbuf);
int exsist=0;
for (int i=0;i<result_group.GetCount();i++)
{
if (target==result_group[i].two_sum)
{
cout<<"\n"<<target<<"的index1="<<result_group[i].this_index<<",index2="<<result_group[i].next_index<<endl;
cout<<"\n"<<target<<"的index1的值="<<original[result_group[i].this_index]<<",index2的值="<<original[result_group[i].next_index]<<endl;
exsist=1;
}
char msgbuf[100];
sprintf(msgbuf,"\n %d %d, %d",result_group[i].two_sum,result_group[i].this_index,result_group[i].next_index);
OutputDebugStringA(msgbuf);
}
if (exsist==0)
{
cout<<"\n"<<target<<"没有可以满足的index"<<endl;
}
cout<<"是否继续(输入#结束)"<<endl;
cin>>con;
}
result_group.RemoveAll();
system("PAUSE");
return 0;
}