Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
Show Similar Problems
大致的问题:给定一个整形数组,返回一个两数之和等于给定目标的目录。你可以假定每次输入只有一个解决办法
我首先想到的是,一个一个的解决,时间复杂度为(n²),空间复杂度为(1)
代码如下,结果是当数组的长度过大时,会超时。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> results; auto len = nums.size(); for (int i = 0; i<len || nums[i] >= target; ++i) { int j = i + 1; for (; j<len || nums[j] > target; ++j) { if ((nums[i] + nums[j]) == target) { results.push_back(i); results.push_back(j); break; } } if ((nums[i] + nums[j]) == target) break; } return results; } }
只能牺牲空间复杂度,来提升时间复杂度。而且题目中的tags有hash table,在C++中可以用map来代替,于是求得下列结果
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; map<int, int> m; if (nums.size() < 2) return result; for (int i = 0; i < nums.size(); i++) m[nums[i]] = i;//建立hash表 map<int, int>::iterator it; for (int i = 0; i < nums.size(); i++) { if ((it = m.find(target - nums[i])) != m.end()) { if (i == it->second) continue; result.push_back(i); result.push_back(it->second);//将结果放入到result中 return result; } } return result; } };