题目://在一个Vector里找到两个和为指定数的下标(假设有且仅有一对)
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].
------------------------------------------------------解法分割线-----------------------------------------------
最简单无脑的一种解法:(找两圈)//时间花费为:816ms,击败了4%的人…………
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
for (int i = 0; i<nums.size(); i++) {
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
answer.push_back(i);
answer.push_back(j);
}
}
}
return answer;
}
};
运行结果如图:
调用map之后的解法://42ms,时间复杂度为O(n),效率大大提升了!
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
map<int, int> mapping;
int tofind;
for (int i = 0; i<nums.size(); i++) {
tofind = target - nums[i];
if (mapping[tofind] != 0) {
answer.push_back(mapping[target - nums[i]] - 1);
answer.push_back(i);
}
mapping[nums[i]] = i + 1;
}
return answer;
}
};
调用unordered_map的解法://22ms
//后来发现,mapping[tofind]!=0也会在mapping里添加一个映射,也就是把tofind加入到了map里,不过好像对结果没什么影响,但肯定不好。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
unordered_map<int, int> mapping;
int tofind;
for (int i = 0; i<nums.size(); i++) {
tofind = target - nums[i];
if (mapping[tofind] != 0) {
answer.push_back(mapping[target - nums[i]] - 1);
answer.push_back(i);
}
mapping[nums[i]] = i + 1;
}
return answer;
}
};
参考TopSolution修改后的代码,调用.find()函数,速度更快://16ms
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> answer;
unordered_map<int, int> mapping;
for (int i = 0; i<nums.size(); i++) {
if (mapping.find(target-nums[i]) != mapping.end()) {
answer.push_back(mapping[target - nums[i]] - 1);
answer.push_back(i);
}
mapping[nums[i]] = i + 1;
}
return answer;
}
};
运行结果如图:
祝程序猿和科研狗永远黑发浓密~