今晚看完天下足球之后,在leetcode上最一道题,于是选择了第一道题Two Sum,题目的叙述如下:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
看完这道题,第一想法是用两层for循环来解决,于是提交了如下代码:
class Solution{
public:
vector<int> twoSum(vector<int>& nums, int target) {
int right = 0;
int left = 0;
int flag = 1;
vector<int> result ;
//sort( nums.begin(), nums.end(), cmp );
for( ; right < nums.size() && flag ; right++ )
for( left = right + 1; left < nums.size() && flag; left++ )
{
cout<<"nums["<<right<<"] = "<<nums[right]<<endl;
cout<<"nums["<<left<<"] = "<<nums[left]<<endl;
if( nums[right] + nums[left] == target )
{
cout<<"nums["<<right<<"] = "<<nums[right]<<endl;
cout<<"nums["<<left<<"] = "<<nums[left]<<endl;
result.push_back( right );
result.push_back( left );
flag = 0;
}
}
return result;
}
};
class Solution {
public: vector<int> twoSum(vector<int>& nums, int target)
{
int index;
vector<int> result;
map<int, int> map;
for( index = 0; index < nums.size(); index++ )
{
if( !map.count( nums[index] ) )
map.insert(pair<int, int> (nums[index], index) );
if( map.count( target - nums[index] ) )
{
int n = map[ target - nums[index] ];
if( n < index)
{
result.push_back( n );
result.push_back( index );
}
}
}
return result;
}
};
通过该段代码回想其C++中map的使用方法,尤其是insert()方法。