您的位置:首页 > 其它

1.Two Sum

2016-03-28 23:05 274 查看
今晚看完天下足球之后,在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;
}
};


但是当在网站上提交之后,发现程序运行的效果并不是很好,然后,通过在网上查找,发现可以用map来解决该问题,于是自己写了如下的代码:

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()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  map