写两个水题放松下心情了属于是
1. 两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> umap;
for (int i = 0; i < nums.size(); i ++)
{
if (umap.count(target - nums[i]))
{
return {i, umap[target - nums[i]]};
}
umap[nums[i]] = i;
}
return {-1, -1};
}
};
202. 快乐数
跟bfs搜索的去重(也是这样处理数字)有异曲同工之处
class Solution {
public:
int f(int n)
{
int res = 0;
while (n > 0)
{
res += (n % 10) * (n % 10);
n /= 10;
}
return res;
}
bool isHappy(int n) {
unordered_set<int> set;
while (n != 1)
{
int tmp = f(n);
if (set.find(tmp) != set.end())
return false;
set.insert(tmp);
n = tmp;
}
return true;
}
};
349. 两个数组的交集
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set;
for (auto i : nums1) set.insert(i);
unordered_set<int> res;
for (int i : nums2)
{
if (set.find(i) != set.end())
{
res.insert(i);
}
}
return vector<int>{res.begin(), res.end()};
}
};
242. 有效的字母异位词
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> umap;
for (auto i : s) umap[i] ++;
for (auto i : t) umap[i] --;
for (auto [x, y] : umap)
{
if (y != 0)
return false;
}
return true;
}
};