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
相关推荐
chao_78936 分钟前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
南岩亦凛汀1 小时前
在Linux下使用wxWidgets进行跨平台GUI开发
c++·跨平台·gui·开源框架·工程实战教程
曦月逸霜1 小时前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
galaxy_strive1 小时前
绘制饼图详细过程
开发语言·c++·qt
Unpredictable2223 小时前
【VINS-Mono算法深度解析:边缘化策略、初始化与关键技术】
c++·笔记·算法·ubuntu·计算机视觉
编程绿豆侠3 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
PingdiGuo_guo3 小时前
C++智能指针的知识!
开发语言·c++
Chuncheng's blog4 小时前
CentOS 7如何编译安装升级gcc至7.5版本?
linux·运维·c++·centos
愚润求学6 小时前
【C++】类型转换
开发语言·c++