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
相关推荐
众少成多积小致巨12 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4565 天前
C++进阶(1)——前景提要
c++
夜悊5 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴5 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0015 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾6 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you6 天前
constexpr函数
c++
凡人叶枫6 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫6 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss6 天前
BRpc使用
c++·rpc