今天,想看看LeetCode的第一题是啥,感觉挺有意思,就做了。
题目描述
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].
思路
(1)双重循环,找到两个相加结果为target的数。这种方法效率不高,时间复杂度为O(n^2)。
(2)只需要一次遍历,通过使用hashmap,将时间复杂度缩减为O(n)。
实现过程
创建<value, index>的hashmap,然后遍历 numbers 数组。
如果 numbers[i] 在hashmap中可以找到与之配对的 target-numbers[i] 这个键值,那么结束遍历,返回这两个数的下标;
如果在hashmap中没有找到 target-numbers[i] ,则将 <numbers[i] ,i> 加入到hashmap中,继续遍历。
这样,将遍历过的元素存入hashmap中,不需要重复遍历。
代码
方法(1)
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int val = target - numbers[i];
for (int j = i+1; j < numbers.size(); j++) {
if (numbers[j] == val) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
}
方法(2)
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> hashMap;
vector<int> result;
int val;
for (int i = 0; i < numbers.size(); i++) {
val = target - numbers[i];
if (hashMap.find(val) != hashMap.end()) {
result.push_back(hashMap[val]);
result.push_back(i);
return result;
}
hashMap[numbers[i]] = i;
}
return result;
}