版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyrususie/article/details/89366540
Two Sum
Problem Link
Description
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.
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution 1
Time complex:
Space complex:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int numsLen = nums.size();
for (int i = 0; i < numsLen; i++) {
for(int j = i+1; j < numsLen; j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
Solution 2
Time complex:
Space complex:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> computeAns;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (computeAns.find(complement) != computeAns.end()) {
return {computeAns[complement], i};
}
computeAns[nums[i]] = i;
}
return{};
}
};
Summary
- return{i, j} 是将i和j结合成一个vector返回的意思
- unordered_map 要#include<unordered_map> 它的find函数返回的是对应元素的迭代器或者是unordered_map::end如果找不到此元素