LeetCode 1. 两数之和

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

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

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

顺序遍历数组,将已经遍历过的元素存在哈希表中,如果当前元素在哈希表中找到匹配值,则返回:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashTbl;

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

        return {0, 0};
    }
};

时间复杂度O(n),空间复杂度O(n),n为输入元素数量。

posted @ 2021-01-08 20:27  epiphanyy  阅读(11)  评论(0)    收藏  举报  来源