代码随想录算法训练营Day5

242.有效的字母异位词

力扣题目链接:. - 力扣(LeetCode)

数组实现简单哈希表

java 复制代码
class Solution {
    public boolean isAnagram(String s, String t) {
            if(s.length()!=t.length()){
                return false;
            }
            int[] record=new int[26];
            for(int i=0;i<s.length();i++){
                record[s.charAt(i)-'a']++;
            }
            for(int i=0;i<t.length();i++){
                record[t.charAt(i)-'a']--;
            }
            for(int i=0;i<record.length;i++){
                if(record[i]!=0){
                    return false;
                }
            }
            return true;
    }
}

349. 两个数组的交集

力扣题目链接:. - 力扣(LeetCode)

HashSet实现哈希表

java 复制代码
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1=new HashSet<>();
        Set<Integer> set2=new HashSet<>();
        for(int i:nums1){
            set1.add(i);
        }
        for(int i:nums2){
            if(set1.contains(i)){
                set2.add(i);
            }
        }
        int[] result=new int[set2.size()];
        int index=0;
        for(Integer i:set2){
            result[index]=i;
            index++;
        }
        return result;

    }
}

202. 快乐数

力扣题目链接:. - 力扣(LeetCode)

HashSet实现哈希表

java 复制代码
class Solution {
    public boolean isHappy(int n) {
        if(n==1)
        return true;
    Set<Integer> set1=new HashSet<>();
    while(!set1.contains(n)){   
        set1.add(n);
        n=getNextNum(n);
        if(n==1)
        return true;
    }
    return false;
    }
    public int getNextNum(int i){
        int sum=0;
        while(i>0){
            sum+=(i%10)*(i%10);
            i/=10;
        }
        return sum;
    }
}

1. 两数之和

力扣题目链接:. - 力扣(LeetCode)

map集合实现哈希表

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];
        Map<Integer,Integer> ed=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(ed.containsKey(target-nums[i])){
                result[0]=ed.get(target-nums[i]);
                result[1]=i;
            }
            ed.put(nums[i],i);
        }
        return result;
    }
}
相关推荐
Cthy_hy3 分钟前
Python算法竞赛:集合去重+字典映射 核心用法一站式整理
数据结构·python·算法
Deepoch10 分钟前
Deepoc数学大模型:驱动发动机行业数智化转型的底层解
人工智能·算法·deepoc·数学大模型
happymaker062612 分钟前
LeetCodeHot100——盛水最多的容器
数据结构·算法·leetcode·双指针·hot100
3DVisionary13 分钟前
蓝光三维扫描:磁性轴承全尺寸精密3D检测方案
算法·3d·3d检测·蓝光三维扫描·精密检测·磁性轴承·圆度测量
过期动态19 分钟前
【LeetCode 热题 100】三数之和
java·数据结构·算法·leetcode·职场和发展·排序算法
逻辑君23 分钟前
Foresight研究报告【20260010】
人工智能·算法·机器学习
weixin_4684668528 分钟前
大语言模型原理新手入门指南
人工智能·python·算法·语言模型·自然语言处理·transformer·注意力机制
z2005093031 分钟前
今日算法(回溯找IP,加检测)
算法·leetcode
sheeta199836 分钟前
LeetCode 补拙笔记 日期:2026.05.29 题目:1559. 二维网格图中探测环
笔记·算法·leetcode
罗超驿37 分钟前
10.滑动窗口解决:无重复字符的最长子串 | LeetCode 3 Java 题解
java·算法·leetcode·面试