闲来无事,在leetcode上做了一道题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
同一组合不能出现两次,必须对已经出现的组合进行标识,不然最后的结果集合会出现两组相同的元素。
代码如下,两层for循环,数据量特别大的时候,会不会影响程序运行速度?这里我暂时还没想到好的处理方法:
int GetMapRet( map<int,int> pass, int bIndex, int aIndex )
{
if( pass.empty() )
return -1;
map<int,int>::iterator it;
it = pass.begin();
bool bFlag = false;
bool aFlag = false;
while(it != pass.end())
{
int index = it->first;
int bUsed = it->second;
if( ( index == bIndex ) && bUsed )
{
bFlag = true;
}
if( ( index == aIndex ) && bUsed )
{
aFlag = true;
}
it ++;
}
if( aFlag && bFlag)
return 0;
return -1 ;
}
//
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> results( 0 ) ;
map<int,int> flag ;//对于已经求和的组合 不再计算
for( int eleNum =0; eleNum < nums.size(); eleNum ++ )
{
for ( int freeNum = 0; freeNum < nums.size() ; freeNum ++ )
{
if( freeNum == eleNum )
continue;
int sum = nums[eleNum] + nums[ freeNum ];
if( ( target == sum ) )
{
int ret = GetMapRet( flag, eleNum, freeNum );
if( ret )
{
results.push_back( eleNum );
results.push_back( freeNum );
flag[eleNum] = 1;
flag[freeNum] = 1;
}
}
}
}
return results;
}
如果freeNum 初始值为-1的话,内循环走不进去。