- 第十五天
- 1.hash_map
前面说到了hash_map就类似于python中的dict词典,一个括号里的值,对应外面的一个值。
下面是一些基本用法
#include
Output
Map : 1 Python 2 C 3 Java 4 PHP 5 C++ 6 Pearl 7 Javascript 8 R Programming 9 Scala 10 Rust After removing 2 elements from the map 1 Python 2 C 3 Java 4 PHP 5 C++ 6 Pearl 7 Javascript 8 R Programming After removing multiple elements from the map 1 Python 2 C 3 Java 4 PHP 5 C++ Size of the map5 Key-value pair present : 2->C Key-value pair not present in a map
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
做起来很简单的,一遍出了,xs
第一种
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
if (s == t)
return true;
return false;
}
};
第二种,新学的hash_map
也是比较简单
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
vector dig(26);
for (auto ch:s){
dig[ch - 'a']++;
}
for (auto ch:t){
dig[ch - 'a']--;
if (dig[ch - 'a'] < 0)
return false;
}
return true;
}
};
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
class Solution {
public:
vector> groupAnagrams(vector& strs) {
unordered_map> mp;
for (string& str: strs) {
string key = str;
sort(key.begin(), key.end());
mp[key].emplace_back(str);
}
vector> ans;
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};
两数之和
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};



