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
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;
}
};
原文:http://www.cnblogs.com/csudanli/p/5304129.html