代码随想录-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;
    }
};
相关推荐
Swift社区27 分钟前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode
逝玄27 分钟前
关于图灵停机问题不可判定性证明
算法·计算机科学
低客的黑调39 分钟前
为你的项目选择一个适合的[垃圾收集器]
java·jvm·算法
芬加达1 小时前
leetcode34
java·数据结构·算法
资深web全栈开发1 小时前
LeetCode 1015. 可被 K 整除的最小整数 - 数学推导与鸽巢原理
算法·leetcode·职场和发展
leoufung1 小时前
链表题目讲解 —— 删除链表的倒数第 n 个节点(LeetCode 19)
数据结构·leetcode·链表
dragoooon341 小时前
[优选算法专题八.分治-归并 ——NO.46~48 归并排序 、数组中的逆序对、计算右侧小于当前元素的个数]
数据结构·算法·排序算法·分治
CoderYanger1 小时前
优选算法-队列+宽搜(BFS):72.二叉树的最大宽度
java·开发语言·算法·leetcode·职场和发展·宽度优先·1024程序员节
招摇的一半月亮2 小时前
P2242 公路维修问题
数据结构·c++·算法