https://leetcode.cn/problems/two-sum/description/

本质还是根据一个key对哈希表进行查询

<aside> 💡

思路:target确定了,那么能和一个数相加得到target的值也唯一确定。

使用这个数本身作为key查询互补数,或是使用其互补数作为key查询这个数都行。

由于不仅需要存储数的值还需要存储其对应的下标,所以使用map构建哈希表

</aside>

vector<int> twoSum(vector<int>& nums, int target) {
    // <差值, 下标>
    unordered_map<int, int> mp;

    for (int i = 0; i < nums.size(); ++i) {
        auto it = mp.find(nums[i]);
        if (it == mp.end()) {
            mp.insert({ target - nums[i], i });
        } else {
            return { it->second, i };
        }
    }
    return { 0, 0 };
}