您的位置:首页 > 其它

LeetCode twoSum

2016-03-21 22:30 429 查看
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

Hide Tags

Array Hash Table

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;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: