目录
242.有效的字母异位词
class Solution {
public:
bool isAnagram(string s, string t) {
int tmp[26]={0};
for(auto str:s)
{
tmp[str-'a']++;
}
for (auto str:t)
{
tmp[str-'a']--;
if (tmp[str-'a']<0)return false;
}
for (auto ii:tmp)
{
if (ii!=0)return false;
}
return true;
}
};
349. 两个数组的交集
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> ans;
unordered_set<int> tmp(nums1.begin(),nums1.end());
for(auto num:nums2){
if (tmp.find(num)!=tmp.end()){
ans.insert(num);
}
}
return vector<int>(ans.begin(),ans.end());
}
};
202. 快乐数
class Solution {
public:
int getHappy(int n){
int newnum = 0;
int tmp = 0;
while (n!=0){
tmp = n%10;
newnum+=tmp*tmp;
n /=10;
}
return newnum;
}
bool isHappy(int n) {
unordered_set<int> dic;
while(n!=1){
if(dic.find(n)!=dic.end())return false;
else dic.insert(n);
n = getHappy(n);
}
return true;
}
};
1. 两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int,int>map;
for(int ii=0;ii<nums.size();ii++){
int k = target-nums[ii];
if (map.find(k)!=map.end()){
return {map.find(k)->second,ii};
}
else{
map.insert(pair<int,int>(nums[ii],ii));
}
}
return {};
}
};
454.四数相加II
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int> umap;
for (int a:nums1){
for (int b:nums2){
umap[a+b]++;
}
}
int ans = 0;
for(int c:nums3){
for(int d:nums4){
if (umap.find(-c-d)!=umap.end()){
ans+=umap[-c-d];
}
}
}
return ans;
}
};
383. 赎金信
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int tmp[26] = {0};
if (ransomNote.size()>magazine.size())return false;
for(auto str:magazine){
tmp[str-'a']++;
}
for(auto str:ransomNote){
if(--tmp[str-'a']<0)return false;
}
return true;
}
};