代码随想录算法训练营第六天 | 哈希表

242.有效的字母异位词

也可使用26位数组进行字母频率统计 (需要适应这种思路,可以引申到桶排序)

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    HashMap<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < s.length(); i++){
        map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
    }
    for (int i = 0; i < t.length(); i++){
        if (!map.containsKey(t.charAt(i))) return false;
        if (map.get(t.charAt(i)) == 1) map.remove(t.charAt(i));
        else map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
    }
    return map.size() == 0;
}

349. 两个数组的交集

使用stream()输出最终结果到数组:

return resSet.stream().mapToInt(x -> x).toArray();

public int[] intersection(int[] nums1, int[] nums2) {
    HashSet<Integer> set1 = new HashSet<>();
    for (int n: nums1){
        set1.add(n);
    }
    HashSet<Integer> set2 = new HashSet<>();
    for (int n: nums2){
        set2.add(n);
    }
    List<Integer> list = new ArrayList<>();
    for (int n: set1){
        if (set2.contains(n)) {
            list.add(n);
        }
    }
    int[] res = new int[list.size()];
    for (int i = 0; i < res.length; i++){
        res[i] = list.get(i);
    }
    return res;
}

202. 快乐数

使用循环特征进行Hash Set存储(题目关键信息)

需要注意在每层while loop中n的更新

public boolean isHappy(int n) {
    HashSet<Integer> set = new HashSet<>();
    while(n != 1){
        int sum = getSum(n);
        if (!set.add(sum)) return false;
        n = sum;
    }
    return true;
}

private int getSum(int n){
    int sum = 0;
    while (n != 0){
        sum += (n % 10) * (n % 10);
        n /= 10;
    }
    return sum;
}

1. 两数之和

典中典,可以结合two sum系列问题

public int[] twoSum(int[] nums, int target) {
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++){
        if (map.containsKey(nums[i])) return new int[]{map.get(nums[i]), i};
        map.put(target - nums[i], i);
    }
    return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值