Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.
You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0,1].
用暴力搜索,算法的时间复杂度是O(n^2)
/**
* Time Limit Exceeded
*/
class Solution {
public:
vector<int>twoSum(vector<int>&numbers, int target)
{ vector<int> res;
for (int i = 0; i < numbers.size(); ++i) {
for (int j = i + 1; j < numbers.size(); ++j) {
if (numbers[j] + numbers[i] == target) {
res.push_back(i + 1);
res.push_back(j + 1);
}
}
}
return res;
}
};
那么只能想个O(n)的算法来实现,整个实现步骤为:先遍历一遍数组,建立map数据,然后再遍历一遍,开始查找,找到则记录index。代码如下:
class Solution {
public: vector<int> twoSum(vector<int> & nums, int target)
{ unordered_map<int,int> m;
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
m[nums[i]] = i;
}
for (int i = 0; i < nums.size(); ++i) {
int t = target - nums[i];
if (m.count(t) && m[t] != i) {
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
};
更简单的写法
class Solution {
public: vector<int> twoSum(vector<int> & nums, int target) {
unordered_map<int,int> m;
for (int i = 0; i < nums.size(); ++i) {
if (m.count(target - nums[i])) {
return {i, m[target - nums[i]]};
}
m[nums[i]] = i;
}
return {};
}
};
网友评论