算法之哈希表

哈希表(散列表)定义:
哈希冲突:

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;
}

leetcode349

/**
 * 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可厉害的土豆

你的鼓励是我创作的源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值