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:
看完这道题,第一想法是用两层for循环来解决,于是提交了如下代码:
但是当在网站上提交之后,发现程序运行的效果并不是很好,然后,通过在网上查找,发现可以用map来解决该问题,于是自己写了如下的代码:
通过该段代码回想其C++中map的使用方法,尤其是insert()方法。
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()方法。
相关文章推荐
- android Google Map获取地理位置信息的方法
- Spark RDD API详解(一) Map和Reduce
- Python中map()函数浅析
- Android使用Google Map浅谈
- Erlang中的映射组Map详细介绍
- c++中map的基本用法和嵌套用法实例分析
- 百度地图给map添加右键菜单(判断是否为marker)
- JavaScript中实现Map的示例代码
- jquery中map函数与each函数的区别实例介绍
- jquery中map函数遍历数组用法实例
- jquery与google map api结合使用 控件,监听器
- jquery遍历数组与筛选数组的方法
- JavaScript中实现map功能代码分享
- 用json方式实现在 js 中建立一个map
- Android Map新用法:MapFragment应用介绍
- js Map List 遍历使用示例
- java实现遍历Map的方法
- velocity显示List与Map的方法详细解析
- Google Map Api和GOOGLE Search Api整合实现代码
- 关于STL中的map容器的一些总结