代码随想录算法训练营DAY6第三章 哈希表part01

目录

[242. 有效的字母异位词](#242. 有效的字母异位词)

[349. 两个数组的交集](#349. 两个数组的交集)

[202. 快乐数](#202. 快乐数)

[1. 两数之和](#1. 两数之和)


242. 有效的字母异位词

cpp 复制代码
class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char,int> map;
        for(int i=0;i<s.size();i++){
            map[s[i]]++;
        }
        for(int i=0;i<t.size();i++){
            if(map[t[i]]){
                map[t[i]]--;
                if(map[t[i]]==0){
                    map.erase(t[i]);
                }
            }
            else {
                return false;
            }
        }
        if(map.size()){
            return false;
        }
        return true;
    }
};

49. 字母异位词分组

438. 找到字符串中所有字母异位词

349. 两个数组的交集

cpp 复制代码
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int> map;
        for(int i=0;i<nums1.size();i++){
            if(map[nums1[i]]==0){
                map[nums1[i]]++;
            }
        }
        vector<int> ans;
        for(int i=0;i<nums2.size();i++){
            if(map[nums2[i]]==1){
                ans.push_back(nums2[i]);
                map[nums2[i]]++;
            }
        }
        return ans;
    }
};

350. 两个数组的交集 II

202. 快乐数

cpp 复制代码
class Solution {
public:
    bool isHappy(int n) {
        unordered_map<int, int> map;
        map[n]++;
        while (1) {
            int sum = 0;
            while (n) {
                sum += pow(n % 10, 2);
                n /= 10;
            }
            if (sum == 1) {
                return true;
            } 
            else {
                if (map[sum]) {
                    return false;
                } 
                else {
                    map[sum]++;
                    n = sum;
                }
            }
        }
        return false;
    }
};

1. 两数之和

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> map;
        for(int i=0;i<nums.size();i++){
            if(map[target-nums[i]]){
                return {i,map[target-nums[i]]-1};
            }
            map[nums[i]]=i+1;
        }
        return {};
    }
};
相关推荐
ytttr8731 天前
基于MATLAB的一维对流扩散方程数值求解
开发语言·算法·matlab
qq_22589174661 天前
基于Python+Django豆瓣图书数据可视化分析推荐系统 可视化 协同过滤算法 情感分析 爬虫
爬虫·python·算法·信息可视化·数据分析·django
one____dream1 天前
【算法】移除链表元素与反转链表
数据结构·python·算法·链表
memmolo1 天前
【3D测量中的术语:系统误差、随机误差、精密度、准确度】
算法·计算机视觉·3d
睡不醒的kun1 天前
不定长滑动窗口-基础篇(2)
数据结构·c++·算法·leetcode·哈希算法·散列表·滑动窗口
霑潇雨1 天前
题解 | 分析每个商品在不同时间段的销售情况
数据库·sql·算法·笔试
金枪不摆鳍1 天前
算法-动态规划
算法·动态规划
季明洵1 天前
Java中哈希
java·算法·哈希
jaysee-sjc1 天前
【练习十】Java 面向对象实战:智能家居控制系统
java·开发语言·算法·智能家居
cici158741 天前
基于MATLAB实现eFAST全局敏感性分析
算法·matlab