hot100 |一、哈希

1-leetcode1. 两数之和

注意:√

  1. 经典老题,用hashMap做就好了
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int need = target - nums[i];
            if (hashMap.containsKey(need)){
                return new int[]{i, hashMap.get(need)};
            }else {
                hashMap.put(nums[i], i);
            }
        }
        return new int[]{};
    }

2-leetcode49. 字母异位词分组

注意:×

  1. 将字符串eat转到char[]中很巧妙的用到了哈希的思想
  2. 注意groupAnagrams函数中的hashMap.putIfAbsent(code, new LinkedList<>());
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList<>();
        HashMap<String, List<String>> hashMap = new HashMap<>();
        for (String str : strs) {
            String code = encode(str);
            hashMap.putIfAbsent(code, new LinkedList<>());
            hashMap.get(code).add(str);
        }
        for (List<String> value : hashMap.values()) {
            ans.add(value);
        }
        return ans;
    }

    private String encode(String str) {
        char[] code = new char[26];
        for (char c : str.toCharArray()) {
            int index = c - 'a';
            code[index]++;
        }
        return new String(code);
    }

3-leetcode128. 最长连续序列

注意:×

  1. 参考下面图片中的描述,非常好的思路(lc官方题解下面的评论中)
  2. num-1和后面的set.contains(curNum+1) 非常好的操作
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int res = 0;
        for (int num : set) {
            if (set.contains(num-1)){
                continue;
            }
            int curNum = num;
            int curRes = 1;
            while (set.contains(curNum+1)){
                curRes++;
                curNum = curNum+1;
            }
            res = Math.max(res, curRes);
        }
        return res;
    }

lc官网题解下面的评论Teck的解释非常清晰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值