目录
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++)
{
if(hash.count(target - nums[i]))return{i,hash[target - nums[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 arr[128];
for(auto ch:s1)
{
arr[ch]++;
}
for(auto ch:s2)
{
arr[ch]--;
if(arr[ch]<0)return false;
}
return true;
}
};
3.存在重复元素
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
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.字母异位词分组
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;
}
};
把异位词字符串排好序之后都是一样的,所以我们把排完以后相同的字符串作为标志,把这些字符串一个个填进去