[LeetCode]1. Two Sum
来源:互联网 发布:js中的大于等于 编辑:程序博客网 时间:2024/06/11 18:46
1. 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].
分析
- 最直接的暴力解决,但速度慢
- 使用哈希表,用于记录每个数对应的下标,复杂度O(n)
- 如果返回的不是下标,则还可以先排序然后使用两边夹逼方式寻找;但本题要寻找下标,所以这个方法行不通
源码
暴力解决
vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; for(vector<int>::const_iterator it = nums.begin(); it < nums.end(); it++) { for(vector<int>::const_iterator inner = it + 1; inner < nums.end(); inner++) { if (target == (*it + *inner)) { ret.push_back(it - nums.begin()); ret.push_back(inner - nums.begin()); break; } } } return ret; }
使用哈希表
vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; unordered_map<int,int> mapper; for(int i = 0; i < nums.size(); i++) { // 遍历原数组 mapper[nums[i]] = i; // [0,4,3,3] target = 6 int gap = target - nums[i]; // mapper[gap] > i 肯定是要往比索引i大的方向查找 比如[3,2,4] target = 6 // 如果不加入这个条件限制,就会返回[0,0],因为6-3=3,而3在哈希表里,不能是自己了 if(mapper.find(gap) != mapper.end() && mapper[gap] > i) { ret.push_back(i); ret.push_back(mapper[gap]); break; } } return ret; }
0 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- Linux内核协议栈(附5) 协议栈中msghdr结构在2.6版本和4.0版本中的差异
- 测试下dll的编写和调用
- 栈的压入、弹出序列
- 栈溢出笔记1.2 覆盖EIP
- Android开发中对Bitmap的内存优化
- [LeetCode]1. Two Sum
- 进程调度原理
- Xcode常用的高效快捷键
- postgreSQL源码阅读计划
- View与ViewGroup--实现QQ左滑删除
- 【追求进步】二叉树的深度
- android调用第三方软件打开下载的附件
- LintCode_35_翻转链表
- 队列的应用——打印二项展开式(a+b)^k的系数(杨辉三角)