leetcode刷题记录-Two Sum
2015-11-23 23:05
417 查看
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.
解题思路:
利用target减去数组中每个数得到数组的差值数组,以原题中的例子为例:{2,7,11,15}对应的差值数组为{7,2,-1,,6},然后遍历原数组,若差值数组中也包含这个数且对应索引不相等,则返回原数组该值索引与差值数组中的索引。为了让时间复杂度为O(n),差值数据需用哈希map的方式保存。
解题源码:
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.
解题思路:
利用target减去数组中每个数得到数组的差值数组,以原题中的例子为例:{2,7,11,15}对应的差值数组为{7,2,-1,,6},然后遍历原数组,若差值数组中也包含这个数且对应索引不相等,则返回原数组该值索引与差值数组中的索引。为了让时间复杂度为O(n),差值数据需用哈希map的方式保存。
解题源码:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> finder; int index1 = -1; int index2 = -1; for(int i=0; i<nums.size(); ++i){ int _num = target - nums[i]; finder.insert(map<int, int>::value_type(_num, i)); } for(int i=0; i<nums.size(); ++i){ map<int, int>::iterator itr; itr = finder.find(nums[i]); if (itr!=finder.end()){ int j = finder[nums[i]]; if (i!=j){ index1 = min(i, j); index2 = max(i, j); break; } } } vector<int> rst; rst.push_back(index1+1); rst.push_back(index2+1); return rst; } };
相关文章推荐
- 判断一个单向链表中是否有环
- ubuntu搜狗输入法安装
- 优秀博客_Android
- caffe使用python创建lmdb
- SQL语句优化技术分析
- Redis入门
- 为什么基类指针和引用可以指向派生类对象,但是反过来不行?
- 实时天气接口
- 系统版本
- codevs1576 最长严格上升子序列
- Use DevTools
- svn locked; try performing 'cleanup'解决方法
- 优化SQL查询:如何写出高性能SQL语句
- java泛型简单学习
- 工作笔记之juqery
- 小心别让圆角成了你列表的帧数杀手
- vim文档设置
- netstat sysctl 查看tcp连接的当前状态
- 我的Android我做主
- 关于UNPIVOT 操作符