1- Two Sum
2015-08-11 20:55
330 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
超时解法:
优化思路有两个,一个是复制一份,进行排序,查找到该元素的值后,去原数组中寻找下标,然后返回。
另一种,就是利用哈希表,将值和下标对应起来,一次遍历即可。
我实现的是哈希表的方式:
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
超时解法:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> r; for(int i = 0; i < nums.size(); i++) { for(int j = i + 1; j < nums.size(); j++) { if( (nums[i] + nums[j]) == target ) { r.push_back(++i); r.push_back(++j); return r; } } } return r; } };上述算法的复杂度为 n 的平方,超时。
优化思路有两个,一个是复制一份,进行排序,查找到该元素的值后,去原数组中寻找下标,然后返回。
另一种,就是利用哈希表,将值和下标对应起来,一次遍历即可。
我实现的是哈希表的方式:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> r(2); unordered_map<int, int> m; for(int i = 0; i < nums.size(); i++) { if(m.find(target - nums[i]) != m.end()) { r[0] = m[target - nums[i]] + 1; r[1] = i + 1; } else { m.insert(make_pair(nums[i], i)); } } return r; } };
相关文章推荐
- Excel中的数据导入到SqlServer数据库中
- 用链表实现电子词典
- win7上配置基于CUDA计算的Theano深度学习环境
- iOS基础-UIKit框架-高级视图-UIPickerView-实例3:国家选择(图片)
- 简单解决java.lang.IllegalStateException: getOutputStream() has already been called for this
- exception in thread main brut.androlib.err.undefinedresobject resource spec : 0x01010462
- 类的复制构造函数调用
- 前言:关于nagios监控
- php时区 为什么两个语句才能起效 date_default_timezone_set ini_set('date.timezone
- 8.11(web doget方法乱码)
- 前言:关于nagios监控
- object转化为string
- Linux后门入侵检测方法以及工具
- 九度oj 1007
- 教你自己实现一个事件总线EventBus
- 寻找数组中的第二大数
- OC_AddressBook_通讯录写入
- 如何运维网站能让其稳定高效——稳定篇
- Jungle Roads
- hdu 1251 统计难题(字典树·粉刷式标记)