242.有效的字母异位词
哈希法核心就是把数据存起来,所以这个题虽然是在用 数组但是还是哈希法
class Solution {
public:
bool isAnagram(string s, string t) {
//int stor[26]; 这行没初始化会报错
int stor[26] = {0};
for (int i = 0; i < s.size(); i++){
int j = s[i] - 'a';
stor[j]++;
}
for(int i = 0; i < t.size(); i++){
int j = t[i] - 'a';
stor[j]--;
}
for(int i = 0; i < 26; i++){
if(stor[i] != 0){
return false;
}
}
return true;
}
};
349. 两个数组的交集
下面解释了上面那个题为什么不直接用set来做
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;
unordered_set<int> nums_set(nums1.begin(),nums1.end()); //这句话定义了一个nums_set的set, 然后把nums1的数据传进去
for (int num : nums2){
if (nums_set.find(num) != nums_set.end()) {
result_set.insert(num);
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
class Solution {
public:
//int get_sum(){ 这句自己写的函数没写参数,一开始打算在函数中定义函数但是C++不允许
int get_sum(int n){
int sum = 0;
while (n) { //这句自己没写出来,自己考虑的时候想写个for循环一直到这个数结束;
sum += (n % 10) * (n % 10) ;
//sum = sum/10;这句写错了
n = n / 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> set;
while(1) {
int result = get_sum(n);
if (result == 1) {
return true;
}
if(set.find(result) != set.end()) {
return false;
} else {
set.insert(result);
}
n= result;
}
}
};