理论知识
- 哈希表是根据关键码的值而直接进行访问的数据结构,一般用来快速判断一个元素是否出现在集合里
- 映射——哈希函数
- 哈希碰撞
- 线性探测法
- 拉链法
- 常用的哈希结构
- 数组
- set(集合)
- map(映射)
242.有效的字母异位词
class Solution {
public:
bool isAnagram(string s, string t) {
int len1 = s.size();
int len2 = t.size();
int record[26] = { 0 };
for (int i = 0; i < len1; i++)
{
record[s[i] - 'a']++;
}
for (int i = 0; i < len2; i++)
{
record[t[i] - 'a']--;
}
for (int i = 0; i < len1; i++)
{
if (record[i] != 0)
{
return false;
}
}
return true;
}
};
349.两个数组的交集
#include<iosrteam>
#include<unordered_set>
using namespace std;
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
/*set 数据不允许重复,可以去重*/
unordered_set<int> result;
unordered_set<int> nums(nums1.begin(), nums2.end());
for (int i = 0; i < nums2.size(); i++)
{
if (nums.find(nums2[i]) != nums.end())
{
result.insert(nums2[i]);
}
}
return vector<int>(result.begin(), result.end());
}
};
202.快乐之数
class Solution {
public:
int getSum(int temp)
{
long int sum=0;
while (temp > 0)
{
sum += (temp % 10) * (temp % 10);
temp = temp / 10;
}
return sum;
}
bool isHappy(int n)
{
unordered_set<int> count;
while (1)
{
int sum = getSum(n);
if (sum == 1)
{
return true;
}
if (count.find(sum) != count.end())
{
return false;
}
else
{
count.insert(sum);
}
n = sum;
}
}
};
1.两数之和
#include<iosrteam>
#include<unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++)
{
if (map.find(target - nums[i])!=map.end())
{
return { (map.find(target - nums[i]))->second,i };
}
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};
标签:map,vector,return,nums,int,sum,随想录,之数,两数
From: https://www.cnblogs.com/FreeDrama/p/18395660