LeetCode Hot100 哈希相关题目(1、49、128)C++

LeetCode 1

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int,int> hash_map;
        for(int i=0;i<nums.size();i++){
            int another=target-nums[i];
            if(hash_map.count(another))
            {
                res={hash_map[another],i};
                return res;
            }
            hash_map[nums[i]]=i;

        }
        return {};
    }
};

LeetCode 49

cpp 复制代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <cstring>

using namespace std;

/*
遍历unordered_map的方式。在C++中,当你使用范围for循环遍历一个unordered_map时,每个迭代的元素是一个键值对(pair),其中.first是键,而.second是值。因此,你不能直接使用hash_map[key]的方式来访问元素,因为key在这里已经是每个键值对中的键部分,而不是一个索引或键名。你应该使用.second来访问与键关联的值。
还可以这么遍历
for (auto i = dict.begin(); i != dict.end(); i ++ )
{
    res.push_back(move(i -> second));
}

auto是unordered_map<string, vector<string>>::iterator
*/
class Solution
{
public:
    // 对于每组字符串,找到一个中间状态,使得这组里的每个字符串都可以变成这个中间状态
    // ASCII码sort
    // 本来需要将整个字符串copy过去,使用move之后只需要把字符串的首地址赋值过去,可以减少一次拷贝操作,提高效率。
    vector<vector<string>> groupAnagrams(vector<string> &strs)
    {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> hash_map;
        for (auto &str : strs)
        {
            string key = str;
            sort(key.begin(), key.end());            // 中间状态 对string容器排序要使用迭代器
            hash_map[key].push_back(std::move(str)); // 中间状态相同的字符串都存到同一个hashmap的key下,后面对应的vector容器中
        }

        for (auto &item : hash_map)
        {
            res.push_back(std::move(item.second)); // 把迭代器的第二项(异位词vector)放入返回的res中
        }
        return res;
    }
};

int main()
{
    vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
    Solution solution = Solution();
    vector<vector<string>> res = solution.groupAnagrams(strs);
    cout << "[";
    for (auto i = res.begin(); i != res.end(); i++)
    {
        cout << "[";
        // for (auto &str : *i) // *i解引用迭代器,获取当前vector<string>
        // {
        //     printf(" \"%s\" ", str.c_str());  使用str.c_str()来获取C风格字符串
        // }
        for (auto j = i->begin(); j != i->end(); j++)
        {
            printf("\"%s\"", (*j).c_str());
            if (j != i->end() - 1)
            {
                cout << ",";
            }
        }
        cout << "]";

        if (i != res.end() - 1)
        {
            cout << ",";
        }
    }

    cout << "]\n";

    return 0;
}

LeetCode 128

cpp 复制代码
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
public:
    int longestConsecutive(vector<int> &nums)
    {
        unordered_set<int> hash_set(nums.begin(), nums.end()); // 直接通过迭代器构造,更高效
        // for (auto num : nums)
        // {
        // set没有push_back方法,是insert
        //     hash_set.insert(num);//将nums存入hash_set,作用是去除原数组重复的数字
        // }

        int max_len = 0;
        for (auto num : hash_set)
        {
            // 以这个num作为起点寻找之后的连续数字
            int end = num; // 先将连续数字的最后一个赋值到end,max_len=end-num+1

            if (hash_set.find(num) != hash_set.end() && hash_set.find(num - 1) == hash_set.end())
            // 如果num在hash_set中,但num-1不在hash_set中,则num可视为连续子序列的起点
            {
                cout << "num=" << num << endl;
                // hash_set.erase(num);//用过起点的
                //  开始寻找连续序列
                //  end一个开始等于num,用end来记录连续字符串当前的最后一个数字值
                while (hash_set.find(end + 1) != hash_set.end()) // 当end的后一个值也在hash_set中,则加入连续序列
                {
                    end++;
                    cout << "end=" << end << endl;
                }
                max_len = max(max_len, end - num + 1);
                cout << "max_len=" << max_len << endl;
            }
        }
        return max_len;
    }
};
int main()
{
    vector<int> nums = {100, 4, 200, 1, 3, 2, 4, 2, 6, 1, 1, 101};
    cout << Solution().longestConsecutive(nums) << endl;
}

输出

复制代码
num=6
max_len=1
num=100
end=101
max_len=2
num=1
end=2
end=3
end=4
max_len=4
num=200
max_len=4
4
相关推荐
ziguo11222 小时前
深入浅出 C/C++ 数据类型:从入门到踩坑
linux·c语言·c++·windows·visual studio
白色冰激凌3 小时前
[SECS/GEM研究] (三)SECS-I 串口上消息怎么分块和重传
c++·secs/gem
光头闪亮亮3 小时前
Fyne ( go跨平台GUI )项目实战-项目开发必备基础知识(中)
android·c++·go
光头闪亮亮3 小时前
Fyne ( go跨平台GUI )项目实战-项目开发必备基础知识(下)
android·c++·go
keep intensify3 小时前
最长有效括号
算法·leetcode·动态规划
CoderYanger4 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
_wyt0014 小时前
洛谷 P7912 [CSP-J 2021] 小熊的果篮 题解
c++·队列
choumin5 小时前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式
code_pgf5 小时前
C/C++ 常用容器功能汇总
c语言·开发语言·c++
王维同学6 小时前
Credential Provider、Filter 与 PLAP 的 CLSID 枚举
c++·windows·安全·注册表