- 第一类: 查找有无--set
元素‘a‘是否存在,通常用set:集合
set只存储键,而不需要对应其相应的值。
set中的键不允许重复- 第二类: 查找对应关系(键值对应)--dict
元素‘a‘出现了几次:dict-->字典
dict中的键不允许重复- 第三类: 改变映射关系--map
通过将原有序列的关系映射统一表示为其他
可以直接在容器中查找。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size()>nums2.size())
swap(nums1, nums2);
vector<int> ans;
int n = nums1.size();
for(int i=0; i<n; i++){
if(find(nums2.begin(), nums2.end(), nums1[i]) != nums2.end()){
if(find(ans.begin(), ans.end(), nums1[i]) == ans.end())
ans.push_back(nums1[i]);
}
}
return ans;
}
};
该题与上题的区别在于,本题的输出允许重复,且出现次数应与该元素在两个数组中出现次数的最小值一致。所以可以选择字典。
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size() > nums2.size())
return intersect(nums2, nums1);
unordered_map<int, int> map;
for(int i : nums1) map[i] ++;
vector<int> ans;
for(int i : nums2) {
if(map.count(i)) {
ans.push_back(i);
map[i] --;
}
if(map[i] == 0) map.erase(i);
}
return ans;
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
int hash1[128];
int hash2[128];
memset(hash1, 0, sizeof(int) * 128);
memset(hash2, 0, sizeof(int) * 128);
for (char c : s) {
hash1[c - ‘0‘] ++;
}
for (char c : t) {
hash2[c - ‘0‘] ++;
}
for (int i = 0; i < 128; i ++) {
if (hash1[i] != hash2[i]) {
return false;
}
}
return true;
}
};
当n不等于1时就循环,每次循环时,将其最后一位到第一位的数依次平方求和,比较求和是否为1。
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> hh;
while(!hh.count(n)){
int sum = 0;
hh.insert(n);
while(n != 0){
sum = sum + (n%10) * (n%10);
n /= 10;
}
n = sum;
}
return n == 1;
}
};
原文:https://www.cnblogs.com/Just-Rejoice/p/13562856.html