Two Sum
2014-04-30 15:48
197 查看
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.Hash map,时间复杂度为O(n),代码实现也比较简单。
2.排序之后用前后两个指针往中间逼近,时间复杂度O(nlogn)。得记录排序前原始的index。
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.Hash map,时间复杂度为O(n),代码实现也比较简单。
vector<int> twoSum(vector<int> &numbers, int target) { vector<int> ans; unordered_map<int, int> numbersMap; unordered_map<int, int>::iterator iter; for (int i = 0; i < numbers.size(); i++) { iter = numbersMap.find(target - numbers[i]); if (iter != numbersMap.end()) { ans.push_back(iter->second); ans.push_back(i + 1); break; } else { numbersMap[numbers[i]] = i + 1; } } return ans; }
2.排序之后用前后两个指针往中间逼近,时间复杂度O(nlogn)。得记录排序前原始的index。
vector<int> twoSum(vector<int> &numbers, int target) { vector<int> ans; vector<int> idx(numbers); int len= numbers.size(); sort(numbers.begin(), numbers.end()); int j=len-1,i=0; while(i<j) { if(numbers[i] + numbers[j] == target) { for(int k=0; k<len; k++) { if(idx[k]==numbers[i]) { ans.push_back(k+1); k++; } if(idx[k]==numbers[j]) ans.push_back(k+1); } return ans; } else if(numbers[i] + numbers[j] < target) i++; else j--; } return ans; }
相关文章推荐
- Two Sum
- Two Sum
- 【LeetCode】Two Sum
- LeetCode 之 Two Sum
- Two Sum
- Two Sum
- 【leetcode】Two Sum
- leetcode之two Sum
- LeetCode: TWO SUM
- [LeetCode 题解]: Two Sum
- LeetCode OJ -Two Sum
- Leetcode_Two Sum
- Two Sum
- [leetcode NO.1] Two Sum (JAVA)
- [LeetCode]Two Sum
- LeeCode--Two Sum
- [C++]LeetCode: 14 Two Sum
- Two Sum | LeetCode OJ 解题报告
- Leetcode[Easy] - Two Sum
- Two Sum