https://leetcode.cn/circle/discuss/mOr1u6/
关键
其实核心是将一个双变量问题,转化为一个单变量问题,用空间来换取时间
使用一个散列表来进行维护
https://leetcode.cn/problems/two-sum/description/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
int tmp = target - nums[i];
auto it = m.find(tmp);
if (it != m.end())
// std::cout << (*it).second << " " << i << std::endl;
return {(*it).second, i};
m[nums[i]] = i;
}
return {};
}
};
例题
https://leetcode.cn/problems/max-pair-sum-in-an-array/
这道题使用的是std::vector
class Solution {
public:
int maxSum(vector<int>& nums) {
std::vector<int> max_val(10, INT32_MIN);
int ans = -1;
for (auto& element : nums) {
int max_d = 0;
int tmp = element;
while (tmp) {
max_d = std::max(tmp % 10, max_d);
tmp /= 10;
// std::cout << "hello" << max_d << std::endl;
}
// std::cout << std::endl;
if (max_val[max_d] != 0) {
ans = std::max(ans, max_val[max_d] + element);
max_val[max_d] = std::max(element, max_val[max_d]);
} else
max_val[max_d] = element;
}
return ans;
}
};