目录
- 1.两数之和
- 2.判定是否互为字符重排
- 3.存在重复元素I
- 4.存在重复元素II
- 5.字母异位词分组
1.两数之和
两数之和
class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int,int> hash;for(int i=0;i<nums.size();i++){int x = target-nums[i];if(hash.count(x)) return {hash[x],i};hash[nums[i]] = i;}//照顾编译器return {-1,-1};}
};
2.判定是否互为字符重排
判定是否互为字符重排
class Solution {
public:bool CheckPermutation(string s1, string s2) {if(s1.size()!=s2.size()) return false;int hash[26] = {0};//使用数组模拟哈希表//将s1放入哈希表中for(auto ch:s1){hash[ch-'a']++;}//判断s2for(auto ch:s2){if(--hash[ch-'a']<0) return false;}return true;}
};
3.存在重复元素I
存在重复元素
class Solution {
public:bool containsDuplicate(vector<int>& nums) {unordered_set<int> hash;for(auto x:nums){if(hash.count(x)) return true;hash.insert(x);}return false;}
};
4.存在重复元素II
存在重复元素II
class Solution {
public:bool containsNearbyDuplicate(vector<int>& nums, int k) {unordered_map<int,int> hash;for(int i=0;i<nums.size();i++){if(hash.count(nums[i])){if(i-hash[nums[i]]<=k){return true;}}hash[nums[i]] = i;}return false;}
};
5.字母异位词分组
字母异位词分组
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {unordered_map<string,vector<string>> hash;vector<vector<string>> ret;//排序for(auto &s:strs){string tmp = s;sort(tmp.begin(),tmp.end());hash[tmp].push_back(s);}//提取出哈希表中的字符数组for(auto& [x,y]:hash){ret.push_back(y);}return ret;}
};