题目描述:
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.
例子:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
分析:
题意:给定一个至少包含两个元素的数组,一个目标值,找到两个数,使得他们的和等于目标值,并返回两个数的下标。假设有且只有一组解。
思路一:遍历两次数组,找到对应解,时间复杂度为O(n²)。
思路二:使用C++ map,其中保存对应key值为数组的元素,对应value值为元素下标。现在考察nums[i]:①如果m[nums[i]]和m[target-nums[i]]都没存在,那么nums[i]加入map中;②如果m[nums[i]]存在,m[target-nums[i]]不存在,说明前者找不到配对,跳过不做处理;③如果m[target-nums[i]]存在,那么现在有nums[i],完成配对、找到答案,保存对应下标返回即可。时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
map<int, int> m;
vector<int> ans(2, 0);
for(int i = 0; i <= n - 1; i++){
if(!m.count(nums[i]) && !m.count(target - nums[i])){
m[nums[i]] = i;
}
else if(m.count(nums[i]) && !m.count(target - nums[i])){
continue;
}
else if(m.count(target - nums[i])){
// debug
// cout << target - nums[i] << ", " << nums[i] << endl;
ans[0] = m[target - nums[i]];
ans[1] = i;
break;
}
}
return ans;
}
};