[LeetCode] Two Sum
2015-04-20 17:57
113 查看
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),代码如下: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
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}; } } } };
相关文章推荐
- Two Sum —— Leetcode
- 【leetcode】1.Two Sum
- 1 leetcode-Two Sum
- LeetCode 001 :Two Sum
- LeetCode-Two sum
- LeetCode之Two Sum
- 【leetcode】Two Sum
- leetcode(1)_two sum
- 【JAVA、C++】LeetCode 001 Two Sum
- LeetCode1-Two Sum
- leetcode: two sum
- LeetCode_Two Sum
- LeetCode-1 Two Sum
- 【leetcode系列】Two Sum
- leetCode 刷题记录-1. Two Sum
- leetcode1--Two Sum
- LeetCode题解——Two Sum
- LeetCode_Two Sum
- LeetCode Online Judge 题目C# 练习 - Two Sum
- leetcode-two sum