当前位置: 首页 > news >正文

哈希表(5题)

目录

1.两数之和

2.判定是否互为字符重排

3.存在重复元素

4.存在重复元素2

5.字母异位词分组


1.两数之和

. - 力扣(LeetCode)

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

我们只需要一边判定一边把数组中的内容往里面塞即可 

2.判定是否互为字符重排

. - 力扣(LeetCode)

class Solution {
public:bool CheckPermutation(string s1, string s2) {if(s1.size() != s2.size())return false;int arr[128];for(auto ch:s1){arr[ch]++;}for(auto ch:s2){arr[ch]--;if(arr[ch]<0)return false;}return true;}
};

3.存在重复元素

. - 力扣(LeetCode)

class Solution {
public:bool containsDuplicate(vector<int>& nums) {unordered_map<int,int>hash;for(auto ch:nums){if(hash.count(ch))return true;hash[ch]++;}return false;}
};

思路同1,一边判断一边把数塞进去

4.存在重复元素2

. - 力扣(LeetCode)

class Solution {
public:bool containsNearbyDuplicate(vector<int>& nums, int k) {unordered_map<int,int>hash;for(int i = 0; i < nums.size(); i++){int x = nums[i];if(hash.count(x) &&  i - hash[x] <= k)return true;hash[x] = i;}return false;}
};

5.字母异位词分组

. - 力扣(LeetCode)

class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {unordered_map<string,  vector<string>  >hash;vector<vector<string>>ret;for(auto ch: strs){string tmp = ch;sort(tmp.begin(),tmp.end());hash[tmp].push_back(ch);}for(auto [x,y]: hash){ret.push_back(y);}return ret;}
};

        把异位词字符串排好序之后都是一样的,所以我们把排完以后相同的字符串作为标志,把这些字符串一个个填进去


http://www.mrgr.cn/news/19886.html

相关文章:

  • 828华为云征文:华为云 Flexus X 实例性能测评——SuperBench 一键窥见性能
  • python-简单的dos攻击
  • App使用Job中遇到的WAIT DEV_NOT_DOZING的解决方案
  • 红黑树总结(RbTree)——C++版
  • 3个免费好用的网站,可以转换PDF,提取MP3
  • LLM大模型学习:AI时代,敏感词过滤,如何精准且高效,方法+代码实现
  • PointNet++改进策略 :模块改进 | PAConv,位置自适应卷积提升精度
  • Axure中继器动态数据图表制作
  • 网恋照妖镜源码搭建教程
  • 【Git 学习笔记_24】Git 使用冷门操作技巧(三)——彩色命令行 + Tab 自动补全 + 自定义状态
  • 【Pandas】Pandas日常工作的常用操作大全
  • 刘润《关键跃升》读书笔记6
  • 【Spring Boot 3】【Web】处理跨域资源共享 CORS
  • 云动态摘要 2024-09-04
  • 手把手教你搭建 Harbor 私有镜像仓库,包含完整的自签证书及验证过程
  • 人工智能顶会IJCAI: 面向惯性传感器信号增强的深度学习架构
  • 网页版修改本地数据器:重新布局,引入 highlight.js高亮显示代码
  • MySQL常用窗口函数总和
  • 连接查询、自关联、子查询
  • torchvision库学习之transforms.Compose(模块)