哈希表(散列表)定义:
哈希冲突:
leetcode242. 有效的字母异位词
思路:
1、记录每个字符出现的下标次数。
bool isAnagram(char* s, char* t) {
int map1[26] = {0};
int map2[26] = {0};
int len1 = strlen(s);
int len2 = strlen(t);
if (len1 != len2)
{
return false;
}
for(int i = 0; i < len1; i++)
{
map1[s[i] - 'a']++;
map2[t[i] - 'a']++;
}
for(int j = 0; j < 26; j++)
{
if(map1[j] != map2[j])
{
return false;
}
}
return true;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
int hash_num[1005] = {0};
int i = 0;
int lessSize = nums1Size > nums2Size ? nums1Size : nums2Size;
int *res = (int *) calloc(lessSize, sizeof(int));
int index = 0;
for(i; i < nums1Size; i++)
{
hash_num[nums1[i]] = 1; // 对出现过的数据标记
}
for(i = 0; i < nums2Size; i++)
{
if (hash_num[nums2[i]] == 1)
{
res[index] = nums2[i];
index++;
hash_num[nums2[i]] = 0; // 对nums1的数据元素值作为数据下标的,在取nums2数组元素值对已经存放的数组做清零。
}
}
*returnSize = index;
return res;
}