LeetCode Two Sum
2014-03-26 16:40
190 查看
题目:
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
方法1:最直观的复杂度为O(n^2),超时。
方法2:先排序,这样的话就要记下以前的索引,转换用时O(n),排序用时O(nlgn),查找用时O(n)。
方法3:使用哈希表(利用stl中的unordered_map实现),边建表,边判断,复杂度为最优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
方法1:最直观的复杂度为O(n^2),超时。
方法2:先排序,这样的话就要记下以前的索引,转换用时O(n),排序用时O(nlgn),查找用时O(n)。
struct node { int val; int idx; node(){} node(int num, int index): val(num), idx(index) {} bool operator < (const node& other) const { return val < other.val; } }; class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> ans(2); vector<node> res(numbers.size()); //O(n) for(int i = 0; i < numbers.size(); i++) res[i] = node(numbers[i], i+1); //O(nlgn) sort(res.begin(), res.end()); int begin = 0, end = numbers.size()-1; //O(n) while(begin < end) { int tmp = res[begin].val + res[end].val; if(target == tmp) { ans[0] = min(res[begin].idx, res[end].idx); ans[1] = max(res[begin].idx, res[end].idx); break; } else if(target > tmp) begin++; else end--; } return ans; } };
方法3:使用哈希表(利用stl中的unordered_map实现),边建表,边判断,复杂度为最优O(n)。
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> ans(2); int len = numbers.size(); unordered_map<int, int> hash_table; for(int i = 0; i < len; i++) { //表中存在与它和为target的数 int other = target - numbers[i]; if(hash_table.find(other) != hash_table.end()) { ans[0] = hash_table[other]; ans[1] = i+1; break; } //不在hash表中,加入 if(hash_table.find(numbers[i]) == hash_table.end()) hash_table[numbers[i]] = i+1; } return ans; } };
相关文章推荐
- 【LeetCode】第1题: Two Sum
- [LeetCode] Two Sum
- Leetcode -- Two Sum
- leetcode之Two Sum
- LeetCode - Two Sum 完整代码(GO)
- 【leetcode】【1】Two Sum
- leetcode No.1 Two Sum
- leetcode------第一题 Two Sum
- LeetCode笔记-A1-Two Sum
- 我的LeetCode第一弹 Leetcode: Two Sum
- LeetCode-Two Sum
- leetcode-Two Sum
- leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)
- LeetCode 01 Two Sum
- leetcode之Two Sum
- leetcode 1 -- Two Sum
- LeetCode|Two Sum
- [Leetcode]之一《two sum》解题报告
- LeetCode-Two Sum
- leetcode Two Sum