Featured image of post 哈希表

哈希表

记录一些C++力扣刷题的常用函数

|
221 字
|

1. 两数之和

Leetcode 1 题,两数之和,难度 Easy

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案,有效答案只有一个

这道题的解题思路比较简单,但是要熟悉哈希表和迭代器。

1

2

3

4

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target)
     {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i)
        {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end())
            {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};

TODO 其他题

使用 Hugo 构建
主题 StackJimmy 设计