问题描述:Two Sum
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, and
you may not use the same element twice.Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1. 暴力穷举
思路:开始的时候我打算用python的itertools库中的combinations函数来直接生成所有的组合,然后再判断是否等于target,如果等于返回这组数,然后再用list的index函数返回i坐标。但这个思路出现了一个问题,给定的list中出现重复的元素时,用index返回坐标会只返回前面的坐标。于是我打算用暴力穷举来实现这个算法。
代码:
class Solution { public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> a;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[j] == target - nums[i]) {
a.push_back(i);
a.push_back(j);
return a;
}
}
}
} };
复杂度:当然这里使用了两层循环,时间复杂度是 O(n2) ,空间复杂度是 O(1) 。
2. map
思路:为了减少时间复杂度,我采用map来存储value和index,这样一来,我们就可以在 O(1) 内找到index了。当然把元素放到map中会耗费我们 O(n) 的复杂度。
代码:
#include<map>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a;
vector<int> result;
for(int i = 0 ; i < nums.size() ; i++)
{
a[nums[i]] = i;
}
for(int i = 0 ; i < nums.size() ; i++)
{
int b = target - nums[i];
map<int,int>::iterator it;
it = a.find(b);
if(a.count(b) && it->second != i)
{
result.push_back(i);
result.push_back(it->second);
return result;
}
}
}
};
复杂度:时间复杂度 O(n) ,空间复杂度 O(1) 。