[LeetCode] Two Sum
2016-07-29 00:00
477 查看
https://leetcode.com/problems/two-sum/
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
这题最先想到的肯定是暴力解法,时间复杂度为o(n2),代码如下:
直接用暴力解法,在 leetcode 上提交会超时(试了下lintcode,暴力解法可以过掉所有测试用例),那有没有更快的方法呢?我最先想到的是利用哈希表,来记录数组元素值与其下标的映射关系,这样只需要对数组遍历一遍即可,时间复杂度为o(n),空间复杂度也是o(n)。在遍历的同时,完成哈希表的查询与插入。代码如下:
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
这题最先想到的肯定是暴力解法,时间复杂度为o(n2),代码如下:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { for (int i = 0; i < numbers.size() - 1; ++i) { for (int j = i + 1; j < numbers.size(); ++j) { if (numbers[i] + numbers[j] == target) { return vector<int>{i + 1, j + 1}; } } } } };
直接用暴力解法,在 leetcode 上提交会超时(试了下lintcode,暴力解法可以过掉所有测试用例),那有没有更快的方法呢?我最先想到的是利用哈希表,来记录数组元素值与其下标的映射关系,这样只需要对数组遍历一遍即可,时间复杂度为o(n),空间复杂度也是o(n)。在遍历的同时,完成哈希表的查询与插入。代码如下:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { unordered_map<int, int> hash; for (int i = 0; i != numbers.size(); ++i) { unordered_map<int, int>::const_iterator itr = hash.find(target - numbers[i]); if (itr == hash.cend()) { hash.insert(make_pair(numbers[i], i)); } else { return vector<int>{itr->second + 1, i + 1}; } } } };
相关文章推荐
- 排序算法总结
- [LeetCode] Permutations II
- 行星运动轨迹的程序实现
- 编程实现LINUX下目录的层层遍历
- 匿名管道
- Linux网络编程9——对TCP与UDP的简易封装2.0
- CPP之内存分配
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- 恶魔的指纹---49幅由算法生成的七芒星图像
- [LeetCode] word ladder II
- 3D有向包围盒与球体碰撞的算法
- Dynamic Programming | Set 3 (Longest Increasing Subsequence)
- 二十进制数的加法
- LINUX输入输出与文件——续
- Linux多线程之互斥
- [Project] SpellCorrect源码详解
- [LeetCode] Copy List with Random Pointer
- [LeetCode] Search in Rotated Sorted Array
- [LeetCode] Swap Nodes in Pairs
- 分形之海岸线