代码随想录算法训练营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;
    }
}
相关推荐
I_belong_to_jesus2 小时前
C++关于分支预测的优化1
开发语言·c++·算法
Code_Solitude9 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司9 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
YLCHUP11 小时前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
思麟呀12 小时前
背包DP(01背包+完全背包)
c++·算法
笑容掩饰我的失落13 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Pniubi14 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
꧁细听勿语情꧂14 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
俊俊几年的15 小时前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c