Problem:
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].
Solution:
1、暴力解法
很容易想到用两个循环嵌套用来遍历Vector数组中的每一个元素,两两相加来和target进行比较,从而返回结果。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> pos;
int len=nums.size();
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++){
if (nums[i]+nums[j]==target) {
pos.push_back(i);
pos.push_back(j);
return pos;
}
}
}
};
2、利用STL中的map对象
由于暴力解法的时间复杂度是O(n^2),虽然此题的测试数据较小,依然ac,但是依然要考虑时间复杂度更小的解法,因此,可以利用map这个键-值对的组合,在map对象中的find()查找的时间复杂度为o(logn),显然要比第一种方法来的效率。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> pos;
map<int,int> map1;
map<int,int>::iterator itr1; //迭代器,相当于容器的指针
int len=nums.size();
for (int i=0;i<len;i++) {map1.insert(pair<int,int>(nums[i],i));}
for (int i=0;i<len;i++){
itr1=map1.find(target-nums[i]);
if((itr1!=map1.end())&(itr1->second!=i)){ //考虑不能重复使用元素
pos.push_back(i);
pos.push_back(itr1->second);
return pos;
}
}
}
};
(注意,map1.insert()函数中不用pair<int,int>可能会出问题,但是目前不知道问题的原因。)