代码随想录算法训练营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;
    }
}
相关推荐
To_OC12 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC3 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode