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].
用暴力搜索,算法的時(shí)間復(fù)雜度是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;
}
};
那么只能想個(gè)O(n)的算法來實(shí)現(xiàn),整個(gè)實(shí)現(xiàn)步驟為:先遍歷一遍數(shù)組芭挽,建立map數(shù)據(jù),然后再遍歷一遍,開始查找古掏,找到則記錄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;
}
};
更簡(jiǎn)單的寫法
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 {};
}
};