一、题目
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
即在一列向量中找到两个数的索引,使两个数相加等于给定的target数值。
Example :
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
二、暴力解法-第一次解题
for循环嵌套,时间复杂度为o()
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> index;
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
int current = nums[i] + nums[j];
if(current == target){
index.push_back(i);
index.push_back(j);
}
}
}
return index;
}
};
三、代码优化
利用unordered_map进行键值对的查找,for循环中每次进行检验看target和num[i]的差值是否在unordered_map对象中,如果不在,就把当前num[i]添加进unordered_map中,以便后面进行检索;如果在就进行返回。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//创建一个unordered_map,内部实现哈希表,无序性导致查找速度很快
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
//count函数由于元素不重复只能为0和1
if (m.count(target - nums[i])) {
return {i, m[target - nums[i]]};
}
//以值为索引
m[nums[i]] = i;
}
return {};
}
};