class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int>s(nums1.begin(), nums1.end());
vector<int>re;
for(auto x:nums2){
if(s.erase(x)) re.push_back(x);
}
return re;
}
};
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
map<int, int>m;
vector<int>re;
for(auto x:nums1) m[x]++;
for(auto y:nums2) {
if(m[y]-->0) re.push_back(y);
}
return re;
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return (s==t);
}
};
- 快乐数
class Solution {
public:
int digitSquareSum(int x){
int re=0;
while(x){
re+=(x%10) * (x%10);
x/=10;
}
return re;
}
bool isHappy(int n) {
int slow=n, fast=n;
while(true){
slow=digitSquareSum(slow);
fast=digitSquareSum(fast);
fast=digitSquareSum(fast);
if(slow==1 || fast==1) return true;
if(fast==slow)
return false;
}
return true;
}
};
- 单词规律
class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char, int> m1;
map<string, int> m2;
stringstream ss(str);
string temp;
for(int i=0; i<pattern.size(); ++i){
ss>>temp;
if(m1[pattern[i]]!=m2[temp])
return false;
m1[pattern[i]]=m2[temp]=i+1;
}
return !(ss>>temp);
}
};
- 同构字符串
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char,char>m1, m2;
for(int i=0; i<s.size(); ++i)
{
if(m1.count(s[i]) && m1[s[i]]!=t[i] || m2.count(t[i]) && m2[t[i]]!=s[i] )
return false;
m1[s[i]]=t[i];
m2[t[i]]=s[i];
}
return true;
}
};