06代码随想录训练营day06|哈希表|LeetCode242、LeetCode349

1、LeetCode242

242. 有效的字母异位词 - 力扣(LeetCode)

bool isAnagram(char * s, char * t){
    // 提前将strlen()函数的值赋给变量,能减少运行时间
    int len_s = strlen(s), len_t = strlen(t);
    // 按以下写法,一定要对比s与t的长度:s("ac"),t("a")
    if (len_t != len_s) return false;
    int hash[26];
    /* 初始化hash数组为0;
     * void *memset(void* s, int c, unsigned long n);
     * 将指针变量s所指向的前n个字节的内存单元用一个“整数”c替换,可以为任何数据类型的数据进行初始化。
     */
    memset(hash, 0 , sizeof(hash));
    for (int i = 0; i < len_s; i++) {
        hash[s[i] - 'a']++;
    }
    for (int i = 0; i < len_t; i++) {
        hash[t[i] - 'a']--;
        if (hash[t[i] - 'a'] < 0) return false;
    }
    return true;
}

 2、LeetCode349

349. 两个数组的交集 - 力扣(LeetCode)

 转C++了,C做这个太痛苦了,用C实现unordered_set,时间上太紧迫

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> hash;
        vector<int> result;
        for (auto i: nums1) {
            hash.insert(i);
        }
        for (auto i: nums2) {
            if (hash.count(i) != 0) {
                result.push_back(i);
                hash.erase(i);
            }
        }
        return result;
    }
};

3、LeetCode202

 202. 快乐数 - 力扣(LeetCode)

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> hash;
        int temp;
        while (true) {
            temp = getSum(n);
            if (temp == 1) return true;
            if (hash.find(temp) == hash.end()) {
                hash.insert(temp);
            } else {
                return false;
            }
            n = temp;
        }
    }
};

 4、LeetCode1

1. 两数之和 - 力扣(LeetCode)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        unordered_map<int, int> map;
        for (int i = 0; i < nums.size(); i++) {
            if (map.count(target - nums[i])) {
                result.push_back(map.at(target - nums[i]));
                result.push_back(i);
                return result;
            } else {
                map.insert(pair<int, int>(nums[i], i));
            }
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值