题目:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Attention: 返回的索引是数组索引加1.
复杂度:
O(n2) runtime, O(1) space – Brute force
超时:
Submission Result: Time Limit Exceeded
Last executed input: [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,
Submission Result: Time Limit Exceeded
| Last executed input: | [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78, |
Code:
注:!!注意函数的输入形参。
vector<int> twoSum(vector<int> &numbers, int target)
<span style="color:#ff6666;">verctor<int> &numbers是引用类型形参</span><span style="color: rgb(51, 51, 51);">,引用形参直接关联到其所绑定的对象,而并非这些对象的副本。</span>
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
//输入是整数数组,并给定目标值。输出和为目标值的两个索引。
//并且题目答案假设是唯一解
//利用遍历的方法 最笨的办法
vector<int> result;
//遍历输入数组
for(int i = 0; i <= numbers.size(); i++)
{
for(int j = i+1; j <= numbers.size(); j++)
{
if(target == numbers[i] + numbers[j])
{
result.push_back(i+1);
result.push_back(j+1);
break;
}
}
}
return result;
}
};
优化方法一:Hash表
复杂度:O(n) runtime, O(n) space – Hash table
思路2:改变数据结构,利用map
Attention: 注意ret的索引是hash[x]+ 1 和 i。
AC Code:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
//换一个数据结构 map
map<int, int> hash;
vector<int> ret;
for(int i = 0; i < numbers.size(); i++)
{
//x即待寻找的匹配值
int x = target - numbers[i];
// map<K,V> m ; m.find(k) 如果m容器中存在按k索引的元素,则返回指向该元素的迭代器,否则,返回超出末端迭代器。m.end()
if(hash.find(x) != hash.end())
{
ret.push_back(hash[x] + 1);
ret.push_back(i + 1);
return ret;
}
//找不到目标值,就插入到map. map<key,value> 插入值:map<numbers[i], i>
//不断地把数组存入map,方便下次查询是否有匹配值。
hash[numbers[i]] = i;
}
return ret;
}
};
1823

被折叠的 条评论
为什么被折叠?



