代码随想录算法训练营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;
    }
}
相关推荐
Magnum Lehar1 分钟前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
水蓝烟雨33 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事40 分钟前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解1 小时前
C++类和对象(上)
开发语言·c++·算法
JKHaaa1 小时前
几种简单的排序算法(C语言)
c语言·算法·排序算法
让我们一起加油好吗1 小时前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
FogLetter1 小时前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
BUG收容所所长2 小时前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
itsuifengerxing2 小时前
python 自定义无符号右移
算法
猎板PCB厚铜专家大族3 小时前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范