目录
0简介
1两数之和
2判定是否互为字符重排
3存在重复元素
4存在重复元素 II
5字母异位词分组
0简介
1两数之和
oj链接:两数之和
解法1
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(nums[i]+nums[j]==target)
{
return {i,j};
}
}
}
return {0,0};
}
};
//解法2
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.find(target - nums[i]) != hash.end())
{
return {hash[target - nums[i]], i};
}
hash[nums[i]] = i;
}
return {0, 0};
}
};
2判定是否互为字符重排
oj链接:判定是否互为字符重排
//解法1
class Solution
{
public:
bool CheckPermutation(string s1, string s2)
{
if (s1.size() != s2.size())
return false;
int hash1[26] = {0}, hash2[26] = {0};
for (auto &s : s1)
hash1[s - 'a']++;
for (auto &s : s2)
hash2[s - 'a']++;
for (int i = 0; i < 26; i++)
{
if (hash1[i] != hash2[i])
return false;
}
return true;
}
};
//优化
class Solution
{
public:
bool CheckPermutation(string s1, string s2)
{
if (s1.size() != s2.size())
return false;
int hash[26] = {0};
for (auto &s : s1)
hash[s - 'a']++;
for (auto &s : s2)
{
if ((--hash[s - 'a']) < 0)
return false;
}
return true;
}
};
3存在重复元素
oj链接:存在重复元素
创建hash<数值,下标>:边存边判断即可
class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
unordered_map<int, int> hash;
for (auto &num : nums)
{
if ((++hash[num]) == 2)
return true;
}
return false;
}
};
4存在重复元素 II
oj链接:存在重复元素 II
创建hash<数值 下标> 进行存储时判断hash里有没有值;如果有将进行判断abs(i-j)<=k;没有进行存储(如果已经储存过了将其覆盖掉:因为判断为true时要两个值越靠近才有可能满足)
// 暴力:三层for循环
class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
unordered_map<int, vector<int>> hash;
for (int i = 0; i < nums.size(); i++)
hash[nums[i]].push_back(i);
for (int i = 0; i < nums.size(); i++)
{
vector<int> tmp = hash[nums[i]];
if (tmp.size() >= 2)
{
for (int i = 0; i < tmp.size(); i++)
{
for (int j = i + 1; j < tmp.size(); j++)
{
if (abs(tmp[i] - tmp[j]) <= k)
return true;
}
}
}
}
return false;
}
};
// 优化
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]) && abs(i - hash[nums[i]]) <= k)
return true;
hash[nums[i]] = i; // 覆盖不影响结果
}
return false;
}
};
5字母异位词分组
oj链接:字母异位词分组
class Solution
{
public:
vector<vector<string>> groupAnagrams(vector<string> &strs)
{
unordered_map<string, vector<string>> hash;
for (auto &str : strs)
{
// 排序
string tmp = str;
sort(tmp.begin(), tmp.end());
hash[tmp].push_back(str);
}
vector<vector<string>> ret;
for (auto &[x, y] : hash)
{
ret.push_back(y);
}
return ret;
}
};
以上便是全部内容;有问题欢迎在评论区指正,感谢观看!