【Leetcode热题100】

哈希

1. 两数之和 

class Solution {
public:
    vector twoSum(vector& nums, int target) {
    //构建hash表    
    unordered_maphash;
    //遍历每个元素数据
    for(int i = 0 ; i < nums.size();++i)
    {
        //目标 - 当前数据 == 与当前设备匹配的元素数据
        auto r = target - nums[i];
        //查询hash表中是否有记载
        if(hash.count(r))return {hash[r] , i};
        //hash表中无记载,把当前数据元素加入到hash表
        hash[nums[i]] = i;
    }
    //没有任何结果返回
    return {};
    }
};

49. 字母异位词分组

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
     //构建哈希表   
    unordered_map>hash;
    // 遍历每一个元素
    for (auto &str : strs)
    {
        //将当前元素赋值给新变量
        string nstr = str;
        //重新排序新的变量
        sort(nstr.begin(),nstr.end());
        //将排序后的变量作为key,原始变量作为value
        hash[nstr].push_back(str);
    }
    //上面的操作把每个元素数据进行归一化,下面输出归一化后的结果
    vector>res;
    for(auto &item : hash)res.push_back(item.second);

    return res;


    }
};

你可能感兴趣的:(数据结构与算法,leetcode,算法,职场和发展)