LeetCode Hot100 (哈希)

1. 两数之和

比较简单,建立个map,看看有没有当前对应的相反的值就可以了

java 复制代码
 class Solution {
    public int[] twoSum(int[] nums, int target) {
        TreeMap<Integer, Integer> arr=new TreeMap<Integer, Integer>();
        int x1=0;
        int x2=0;
        for(int i=0;i<nums.length;i++){

            Integer x=arr.get(target-nums[i]);
            if(x!=null){
                x1=i;
                x2=x;
                return new int[]{x,i};
            }
            arr.put(nums[i],i);
        }
return new int[]{x1,x2};
    }
}

49. 字母异位词分组

排序之后进行hash,如果存在直接放到后面,不存在,新创一个即可,最后通过stream流拿到答案

java 复制代码
import java.util.*;
class Solution {
     public List<List<String>> groupAnagrams(String[] strs) {
        int len =strs.length;
        HashMap<String,List<String>> map =new HashMap<>();
        for(int i=0;i<len;i++){
            char [] chars =strs[i].toCharArray();
            Arrays.sort(chars);
            String key = Arrays.toString(chars);
            if(map.get(key)==null){
                map.put(key,new ArrayList<>());
            }
            map.get(key).add(strs[i]);
        }
        List< List <String>>ans =new ArrayList<>();
        ans=map.values().stream().toList();
        System.out.println(ans);
        return ans;

    }
}

128. 最长连续序列

建议直接排序

java 复制代码
import java.util.*;
class Solution {
     public int longestConsecutive(int[] nums) {
        Arrays.sort(nums);
        int maxx=1;
        int sum=1;
        if(nums.length==0){
            return 0;
        }
        for(int i=1;i<nums.length;i++){
            if(nums[i]==nums[i-1]+1){
                sum++;
            }
            else if(nums[i]==nums[i-1]){
                continue;
            }
            else{
                sum=1;
            }
            maxx=Math.max(sum,maxx);
        }
        return maxx;

    }
}
相关推荐
leiming61 天前
C++ vector容器
开发语言·c++·算法
Xの哲學1 天前
Linux流量控制: 内核队列的深度剖析
linux·服务器·算法·架构·边缘计算
yaoh.wang1 天前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
LYFlied1 天前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
艾醒1 天前
大模型原理剖析——多头潜在注意力 (MLA) 详解
算法
艾醒1 天前
大模型原理剖析——DeepSeek-V3深度解析:671B参数MoE大模型的技术突破与实践
算法
jifengzhiling1 天前
零极点对消:原理、作用与风险
人工智能·算法
鲨莎分不晴1 天前
【前沿技术】Offline RL 全解:当强化学习失去“试错”的权利
人工智能·算法·机器学习
XFF不秃头1 天前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode