【Leetcode】1.两数之和C++(哈希表法)

![在这里插入图片描述](https://img-blog.csdnimg.cn/20200120123802403.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow
哈希表由于可以用 O ( 1 ) O(1) 的时间复杂度查找键值映射(类似于python的字典),通常用于将时间度为 O ( n 2 ) O(n^2) 的问题转换为 O ( n ) O(n)

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
*/
#include "iostream"
#include "vector"
#include "unordered_map"

using namespace std;

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

        for (i = 0; i < nums.size(); i++)
        {
            // 建立哈希映射,从数值num(键)到索引index(值)
            map[nums[i]] = i;
        }

        for (i = 0; i < nums.size(); i++)
        {
            res = target - nums[i];
            // map.count方法返回键值是否存在
            if (map.count(res) && map[res] != i)
                break;
        }

        return { i, map[res] };
    }
};

int main(void)
{
    Solution S;
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;

    S.twoSum(nums, target);

    return 0;
}
发布了64 篇原创文章 · 获赞 121 · 访问量 9012

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104050322