【Day6】Hash table, 242 valid anagrams, 349 intersection of two arrays, 202 happy numbers, 1 sum of two numbers
Hash table theoretical basis
hash table
Hash table (Hash table), also called hash table.
Generally, hash tables are used to quickly determine whether an element appears in the set
242 valid anagrams
Topic link: 242
Define an array record with a size of 26 and initialized to 0, because the ASCII characters from a to z are also 26 consecutive values.
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {
0};
for (int i = 0; i < s.size(); i++) {
// 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
record[s[i] - 'a']++; //a是对应的0下标
}
for (int i = 0; i < t.size(); i++) {
record[t[i] - 'a']--; //在s数组里有几个对应的字母就加几个,在t数组里再逐个减掉
}
for (int i = 0; i < 26; i++) {
if (record[i] != 0) {
// record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
return false;
}
}
// record数组所有元素都为零0,说明字符串s和t是字母异位词
return true;
}
};
349 Intersection of two arrays
Topic link: 349
Use unordered_set to deduplicate
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set; // 存放结果,之所以用set是为了给结果集去重 unord_set做去重操作
unordered_set<int> nums_set(nums1.begin(), nums1.end()); //nums1初始化
for (int num : nums2) {
// 发现nums2的元素 在nums_set里又出现过
if (nums_set.find(num) != nums_set.end()) {
result_set.insert(num);//如果2里的元素在1里出现过 放入result
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
202 happy number
Topic link: 202
class Solution {
public:
// 取数值各个位上的单数之和
int getSum(int n) {
int sum = 0;
while (n) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> set;
while(1) {
int sum = getSum(n);
if (sum == 1) {
return true;
}
// 如果这个sum曾经出现过,说明已经陷入了无限循环了,立刻return false
if (set.find(sum) != set.end()) {
return false;
} else {
set.insert(sum);
}
n = sum;
}
}
};