新版块:散列
具体细节不多赘述,主要使用C++中的STL库,后续会跟进实现手搓STL库。
Leetcode242 有效的字母异位词
题目链接:有效的字母异位词
文章链接:代码随想录-字母异位词
代码:
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {0};
for(int i = 0; i< s.size();i++)
record[s[i]-'a']++;
for(int i = 0; i< t.size();i++)
record[t[i]-'a']--;
for(int j = 0; j < 26; j++)
if(record[j] != 0)
return false;
return true;
}
};
整体思路:“散列”的思想在于以空间换时间,记录必要数据,在但时间内查找。
本题就是直接记录两个字符串中哥哥字母出现的次数,记录在同意数组中,观察是否一致。
Leetcode349 两个数组的交集
题目链接:两个数组的交集
文章链接:代码随想录-两个数组的交集
代码:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result;
int hash[1001] = {0};
for(int num : nums1)
hash[num] = 1;
for(int num : nums2)
if(hash[num] == 1)
result.insert(num);
return vector<int>(result.begin(),result.end());
}
};
思路分析:题中限制了数组中数值的大小,如此便可以将nums1中出现的记录在数组中,(明确数组各位置对应的值),使用unordered_set 数据结构储存最终结果(不会重合的一个集合)
Leetcode202 快乐数
题目链接:快乐数
文章链接:代码随想录-快乐数
代码:
class Solution {
public:
int square(int x)
{
int res = 0;
while(x)
{
int y = x % 10;
x = x / 10;
res += y * y;
}
return res;
}
bool isHappy(int n) {
unordered_set<int> set;
int temp =0;
int x = n;
while(1)
{
temp = square(x);
if(temp == 1)
return true;
if(set.find(temp) == set.end())
set.insert(temp);
else if(set.find(temp) != set.end())
return false;
x = temp;
}
}
};
思路分析:
使用“模拟”思想,进行求和,要每次记录结果,如果某一次的结果已经出现过,那说明已经进入死循环,不可能得到1,那么return false,否则,直到出现1return true。
这里记录已经出现的结果并且要经常查找,必然使用散列表,使用set。
Leetcode1 两数之和
题目链接:两数之和
文章链接:代码随想录-两数之和
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int ,int> mapint;
for(int i = 0; i< nums.size(); i++)
{
auto temp = mapint.find(target-nums[i]);
if(temp != mapint.end())
return {temp->second, i};
else
mapint.insert(pair(nums[i],i));
}
return {};
}
};
思路分析:两数之和比较简单,思想很是朴素,每次会将已遍历的数以及对应的下表保存到map中,在保存前先查找map中有没有可以与当前元素和为target的,如果有,则返回,没有,放进map。