Leetcode-Two Sum
2014-10-07 15:45
302 查看
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
思路:固定一位,找剩下的元素,判断其和是否等于target
时间复杂度O(n^2)
下面做些优化:
find函数的底层实现是红黑树,时间复杂度为O(logn)
所以整个函数的时间复杂度为O(nlogn)
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
思路:固定一位,找剩下的元素,判断其和是否等于target
时间复杂度O(n^2)
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; for(int i=0;i<numbers.size();i++) for(int j=i+1;j<numbers.size();j++) { if(numbers[i]+numbers[j]==target) { res.push_back(i+1); res.push_back(j+1); return res; } } return res; } };提交的结果为:Time Limit Exceeded
下面做些优化:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; res.clear(); multimap<int,int> m; multimap<int,int>::iterator mit; multimap<int,int>::iterator mit2; int i; for(i=0;i<numbers.size();i++){ //m[numbers[i]]=i+1; m.insert(pair<int,int>(numbers[i],i+1)); } for(mit=m.begin();mit!=m.end();mit++) { if((mit2=m.find(target-mit->first))!=m.end()&&mit2!=mit) { if(mit->second>mit2->second) { res.push_back(mit2->second); res.push_back(mit->second); } else { res.push_back(mit->second); res.push_back(mit2->second); } return res; } } return res; } };
find函数的底层实现是红黑树,时间复杂度为O(logn)
所以整个函数的时间复杂度为O(nlogn)
相关文章推荐
- [Leetcode] Two Sum
- 【LeetCode】Two Sum
- LeetCode 001 Two Sum
- LeetCode 1 - Two Sum
- [leetcode] two sum
- leetcode 1 Two Sum
- LeetCode-1.Two Sum
- LeetCode 1. Two Sum
- LeetCode Practice_1 Two Sum
- leetcode - Two Sum
- LeetCode-1- Two Sum
- 【Leetcode】1. Two Sum
- LeetCode 1. Two sum
- leetcode Two Sum 每日一题 (。・∀・)ノ゙嗨
- Two Sum--leetcode
- Leetcode-Two Sum
- LeetCode之1—-Two Sum
- 【Leetcode】【Medium】Two Sum
- leetcode----Two Sum
- leetcode001:Two Sum