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 max_val(10, INT32_MIN);来进行维护,其实是因为数字只存在0-9,很多时候还是需要考虑一下实际情况,不能无脑的使用map,如果使用map我觉得会比这个复杂挺多的

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;
    }
};

Hey!

If you have any non-algorithmic questions about the code, send me a message and I will be happy to help. I also hope to make more like-minded friends.