哈希 STL

哈希表

哈希表的实现可以由三种数据结构实现

Set 集合 Map 映射 unordered_map 无序映射


  • 哈希表算法是一种以空间换时间的算法,可以在判断数据是否重复出现 or 数据去重方面有优异性能

例题:leetcode NO.1两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
哈希代码示例:<leetcode.1>

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> mp;
        for (int i = 1; i <= nums.size(); i++) {
            mp[nums[i - 1]] += i;
            if (mp[target - nums[i]] != 0) {
                return {i, mp[target-nums[i]]-1};
            }
        }
        return {};
    }
};