代码随想录-DAY⑤-哈希表——leetcode 242 | 349 | 202

242

思路

先遍历字符串1,

记录每个字符的个数,

然后遍历字符串2,

挨个减去字符个数,

出现小于零的个数说明字符总数不重合。

时间复杂度:O(n)

空间复杂度:O(1)

代码
cpp 复制代码
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length() != t.length()){
            return false;
        }
        vector<int> table(26, 0);

        for(auto c : s){
            table[c-'a']++;
        }
        for(auto c : t){
            table[c-'a']--;
            if(table[c-'a']<0){
                return false;
            }
        }
        return true;
    }
};

349

思路

先把数组1存到哈希表1中,

然后遍历数组2,

将能在哈希表1中找到的存到哈希表2中,

这样可以去掉重复的,

最后把哈希表2转为数组。

时间复杂度: O(n + m)

空间复杂度: O(n)

代码
cpp 复制代码
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> nums1_set(nums1.begin(), nums1.end());
        unordered_set<int> result_set;
        for(auto i : nums2){
            if(nums1_set.count(i)){
                result_set.insert(i);
            }
        }
        return vector<int>(result_set.begin(), result_set.end());
    }
};

202

思路

申请一个哈希表,

每计算一次快乐数,

都将结果存到哈希表中,

如果发现重复结果说明不是快乐数,

如果发现结果值为1说明是快乐数。

时间复杂度: O(logn)

空间复杂度: O(logn)

代码
cpp 复制代码
class Solution {
public:
    int getnext(int n) {
        int num=0;
        while(n>0){
            num += (n%10)*(n%10);
            n /= 10;
        }
        return num;
    }

    bool isHappy(int n) {
        unordered_set<int> nums;
        while(n!=1){
            if(nums.count(n)){
                return false;
            }
            nums.insert(n);
            n = getnext(n);
        }
        return true;
    }
};
相关推荐
小许学java1 小时前
数据结构-ArrayList与顺序表
java·数据结构·顺序表·arraylist·线性表
格林威3 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特5 小时前
老题新解|大整数加法
数据结构·c++·算法
小刘max6 小时前
深入理解队列(Queue):从原理到实践的完整指南
数据结构
过往入尘土6 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.6 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!6 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大6 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
洲覆6 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
MoRanzhi12037 小时前
15. Pandas 综合实战案例(零售数据分析)
数据结构·python·数据挖掘·数据分析·pandas·matplotlib·零售