LeetCode 1. 两数之和 Two Sum (Easy)

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

来源:力扣(LeetCode)

一次哈希表遍历法。

用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i],如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        
        map<int, int> hashMap;
        vector<int> ret(2, -1);
        for (int i = 0; i < nums.size(); ++i)
        {
            //存在该键值
            if (hashMap.count(target - nums[i]) == 1)
            {
                ret[0] = hashMap[target - nums[i]];
                ret[1] = i;
                break;
            }
            hashMap[nums[i]] = i;
        }
        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12912726.html