哈希【Lecode_HOT100】

1.两数之和No.1

image-20241124173222851

  • 遍历数组
public int[] twoSum(int[] nums, int target) {
        int [] res = new int[2];
        for(int i = 0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;
    }
  • 哈希表
public int[] twoSum(int[] nums, int target) {
        //哈希
        HashMap<Integer,Integer> map = new HashMap<>(); //(值,索引)
        for(int i = 0;i<nums.length;i++){
            int temp = target-nums[i];
            if(map.containsKey(temp)){
                return new int[]{map.get(temp),i};
            }
            map.put(nums[i],i);
        }
        return null;
        
    }
2.字母异位词No.49

image-20241124175432665

public List<List<String>> groupAnagrams(String[] strs) {
        // 创建一个哈希表,用于存储分组
        Map<String, List<String>> map = new HashMap<>();

        for (String str : strs) {
            // 对字符串进行排序
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortedStr = new String(chars);

            // 将排序后的字符串作为键,将原字符串加入对应的列表
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            map.get(sortedStr).add(str);
        }

        // 返回哈希表中的所有值(分组结果)
        return new ArrayList<>(map.values());
    }
3.最长子序列No.128

image-20241124181937683

 public int longestConsecutive(int[] nums) {
        //判断数组中是否有数据
        if(nums.length==0) {
            return 0;
            }

        //创建一个set,目的是去重
        HashSet<Integer> set = new HashSet<>();
        //将数组排序
        Arrays.sort(nums);
        //定义长度
        int length = 1;
        //定义最大值
        int max = 1;
        //遍历数组
        for(int i = 1;i<nums.length;i++){
            if(!set.add(nums[i])) continue;
            if(nums[i-1]+1==nums[i]){
                length++;
                max=Math.max(max,length);
            }else{
                length = 1;
            }
        }
        return max;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值