立志重刷代码随想录60天冲冲冲!!——第五天

242.有效的字母异位词

数组模拟hash表

class Solution {
public:
    bool isAnagram(string s, string t) {
        /* 初始化vector,26个0 */
        vector<int> table(26, 0);
        
        /* 自动迭代器 */
        for (auto &ch: s) {
            table[ch - 'a']++;
        }
        for (auto &ch: t) {
            table[ch - 'a']--;
        }
        for (int i = 0; i < 26; i++) {
            if (table[i] != 0) {
                return false;
            }
        }
        return true;
    }
};

349. 两个数组的交集

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        /* 无须set,unordered_set,初始化需加强 */
        unordered_set<int> res;
        unordered_set<int> nums1_set(nums1.begin(), nums1.end());

        /* nums1_set.find()是会重头遍历,直到最后一个end() */
        for (auto num: nums2) {
            if (nums1_set.find(num) != nums1_set.end()) {
                res.insert(num);
            }
        }
        return vector<int>(res.begin(), res.end());
    }
};

202. 快乐数

需要记一下,如何将一个数字按照每一位拆分

class Solution {
public:
    /* 计算每个数的各个位置平方和,记下来! */
    int GetNum(int num) {
        int sum = 0;
        while(num) {
            sum += (num % 10) * (num % 10);
            num /= 10;
        }
        return sum;
    }

    bool isHappy(int n) {
        unordered_set<int> res;
        while (n != 1) {
            n = GetNum(n);
            if (res.find(n) != res.end()) {
                return false;
            } else {
                res.insert(n);
            }
        }
        return true;

    }
};

1. 两数之和

使用迭代器it

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashmap;
        for (int i = 0; i < nums.size(); i++) {
            // 使用迭代器好一些
            auto it = hashmap.find(target - nums[i]);

            if (it == hashmap.end()) {
                hashmap[nums[i]] = i;
            } else {
                return {it->second, i};
            }
        }
        return {};
    }
};

代码随想录更新 文章被收录于专栏

冲冲冲冲冲冲!

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务