这些题都挺无聊的 ORZ
leetcode 242. 有效的字母异位词 easy
题目描述:
解题思路:
hash表统计词频
代码:
//
class Solution {
public:
bool isAnagram(string s, string t) {
int count[26] = {};
for (char c: s)
count[c - 'a']++;
for (char c:t)
count[c - 'a']--;
for (int num: count)
{
if (num != 0)
return false;
}
return true;
}
};
leetcode 349. 两个数组的交集 easy
题目描述:
解题思路:
hash set 存就完事了
代码:
//
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> hash(nums1.begin(), nums1.end());
unordered_set<int> res;
for (int i: nums2)
{
if (hash.count(i))
res.insert(i);
}
return vector<int>(res.begin(), res.end());
}
};
leetcode 202. 快乐数 easy
题目描述:
解题思路:
模拟这个过程, hashset 用来判断是否当前的数之前出现过就完事了
代码:
//
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> hash;
while (n != 1 && !hash.count(n)){
hash.insert(n);
n = get_next(n);
}
return n==1;
}
int get_next(int n){
int res = 0;
while (n){
res += pow(n%10, 2);
n /= 10;
}
return res;
}
};
leetcode 383. 赎金信 easy
题目描述:
解题思路:
无聊
代码:
//
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int> hash;
for (char c: magazine)
hash[c]++;
for (char c: ransomNote)
{
if (hash.count(c))
{
if (hash[c] <= 0)
return false;
hash[c]--;
}
else
return false;
}
return true;
}
};