1.Two Sum

作者: RobotBerry | 来源:发表于2017-04-29 09:21 被阅读0次

问题

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

输入

Given nums = [2, 7, 11, 15], target = 9

输出

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析

首先考虑枚举两个数字,复杂度为O(n^2)。

但是题目强调了只有一组解,这就意味着数组元素的值可以被用来当做键值,即元素的值当键,元素的下标当值,这样就能通过值来快速查找下标。我们用unordered_map作为关联容器来存储键值对,把查找的复杂度降至O(1)。

要点

  • 把值当键,下标当值,即倒排索引;
  • unordered_map使用hash表作为底层数据结构,虽然不能像map一样保持元素的顺序,但是却能把查找的复杂度降至O(1)(map的查找操作需要O(logn))。

时间复杂度

O(n)

空间复杂度

O(1)

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> umap; // 倒排索引表
        for (int i = 0; i < nums.size(); i++) {
            // 在map中查找有没有元素的键等于目标值减当前值
            // 如果没有,就把当前元素的值和下标插入map中
            // 如果有,就把当前元素的下标和找到的元素的下标返回即可
            if (umap.find(target - nums[i]) == umap.end()) {
                umap[nums[i]] = i;
            }
            else {
                res.push_back(i);
                res.push_back(umap[target - nums[i]]);
            }
        }
        return res;
    }
};

相关文章

网友评论

    本文标题:1.Two Sum

    本文链接:https://www.haomeiwen.com/subject/nqkzzttx.html