首页 > 代码库 > Leetcode | Two Sum
Leetcode | 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
我用的是multimap。因为有可能出现两个数是相同的,比如{4,4,9},target = 8. 因为c++里面map是用红黑树实现的,所以时间复杂度是O(nlgn)。如果改用hash的话,就是O(n)了。
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 vector<int> result; 5 multimap<int, int> tmp; 6 7 for (int i = 0; i < numbers.size(); i++) { 8 tmp.insert(pair<int,int>(numbers[i], i + 1)); 9 } 10 11 int v = target / 2; 12 multimap<int, int>::iterator it2; 13 for (multimap<int,int>::iterator it = tmp.begin(); it != tmp.end() && it->first <= v; it++) { 14 if ((it2 = tmp.find(target - it->first)) != tmp.end()) { 15 if (it->first != it2->first) { 16 result.push_back(it->second); 17 result.push_back(it2->second); 18 break; 19 } else { 20 it2++; 21 if (it2 != tmp.end() && it2->first == it->first) { 22 result.push_back(it->second); 23 result.push_back(it2->second); 24 break; 25 } 26 } 27 } 28 } 29 sort(result.begin(), result.end()); 30 return result; 31 } 32 };
同样的,可以先用排序,然后用两个指针从左右往中间扫。但是注意一点是,排序的时候要保存每个数对应的原来的位置。时间复杂度就是O(nlgn)。
1 class Solution { 2 public: 3 struct Num { 4 int val; 5 int pos; 6 Num(int v, int p):val(v),pos(p) {} 7 }; 8 9 static bool comparor(const Num &n1, const Num &n2) { 10 return n1.val < n2.val; 11 } 12 13 vector<int> twoSum(vector<int> &numbers, int target) { 14 vector<int> result; 15 vector<Num> nums; 16 for (int i = 0; i < numbers.size(); ++i) { 17 nums.push_back(Num(numbers[i], i + 1)); 18 } 19 sort(nums.begin(), nums.end(), comparor); 20 21 int i = 0, j = nums.size() - 1, s; 22 23 while (j > i) { 24 s = nums[i].val + nums[j].val; 25 if (s == target) { 26 result.push_back(nums[i].pos); 27 result.push_back(nums[j].pos); 28 sort(result.begin(), result.end()); 29 return result; 30 } else if (s > target) { 31 j--; 32 } else { 33 i++; 34 } 35 } 36 return result; 37 } 38 };
comparor函数必须是static的,而且参数类型必须都是const。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。