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;

    }
}
相关推荐
大熊背35 分钟前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2581 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲1 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力552 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜2 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者2 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂2 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_2 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.3 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks3 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程