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;

    }
}
相关推荐
想做小南娘,发现自己是女生喵1 小时前
【无标题】
数据结构·算法
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎3 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀4 小时前
约瑟夫环问题
算法
科技大视界6 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴6 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe6 小时前
算法滑动窗口
数据结构·算法
怪兽学LLM6 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
可编程芯片开发6 小时前
基于PI控制的三相整流器控制系统的simulink建模与仿真,包含超级电容充电和电机
算法