代码随想录算法训练营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;
    }
}
相关推荐
Scc_hy1 小时前
强化学习_Paper_2000_Eligibility Traces for Off-Policy Policy Evaluation
人工智能·深度学习·算法·强化学习·rl
leke20032 小时前
2025年10月17日
算法
CoovallyAIHub2 小时前
Mamba-3震撼登场!Transformer最强挑战者再进化,已进入ICLR 2026盲审
深度学习·算法·计算机视觉
Aqua Cheng.2 小时前
代码随想录第七天|哈希表part02--454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
java·数据结构·算法·散列表
怀揣小梦想2 小时前
跟着Carl学算法--哈希表
数据结构·c++·笔记·算法·哈希算法·散列表
Nebula_g2 小时前
Java哈希表入门详解(Hash)
java·开发语言·学习·算法·哈希算法·初学者
Kent_J_Truman2 小时前
【模拟散列表】
数据结构·算法·蓝桥杯·散列表·常识类
Lchiyu2 小时前
哈希表 | 454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和
算法
玩镜的码农小师兄2 小时前
[从零开始面试算法] (04/100) LeetCode 136. 只出现一次的数字:哈希表与位运算的巅峰对决
c++·算法·leetcode·面试·位运算·hot100
RTC老炮2 小时前
webrtc弱网-AcknowledgedBitrateEstimatorInterface类源码分析与算法原理
网络·算法·webrtc