Loading

1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

你可以按任意顺序返回答案。

  • 利用hash表,只需遍历一次数组,没有查到结果的,都存入hash表,从hash表中查询的是和-当前元素。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
        unordered_map<int, int> hashtable;
        for (int i = 0; i < n; i++) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) return {i, it->second};
            hashtable[nums[i]] = i;
        }
        return {};
    }
};
posted @ 2025-03-02 23:02  lotuslaw  阅读(4)  评论(0)    收藏  举报