今晚看完天下足球之后,在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()方法。

本文详细介绍了如何通过TwoSum问题理解并应用C++中的map数据结构,从传统的双层循环解决方案到更高效的使用map实现,提高了代码效率。文章还回顾了C++中map的插入方法insert()的使用,并提供了实际代码示例。
824

被折叠的 条评论
为什么被折叠?



