第三章 哈希表part01

使用场景:当判断一个数据是否出现过时 第一时间想到哈希法

242.有效的字母异位词

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] record = new int[26];
        for(int i = 0; i < s.length();i++){
            record[s.charAt(i)-'a']++;
        }
        for(int j = 0; j < t.length() ; j++){
            record[t.charAt(j)-'a']--;
        }
        for(int c = 0; c<26;c++){
            if(record[c] != 0){
                return false;
            }
        }
        return true;

    }
}

349.两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1 == null || nums2 == null || nums1.length == 0|| nums2.length ==0){
            return new int[0];
        }
        Set<Integer> set = new HashSet<>();
        Set<Integer> intersect = new HashSet<>();
        for(int i = 0;i < nums1.length;i++){
            set.add(nums1[i]);
        }
        for (int i = 0;i<nums2.length;i++){
            if(set.contains(nums2[i])){
                intersect.add(nums2[i]);
            }
        }
        int count = 0;
        int[] result = new int[intersect.size()];
        for(int num: intersect){
            result[count++]=num;
        }
        return result;

    }
}

202.快乐数

class Solution {
    
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while(n!=1){
           if(set.contains(n)){
               return false;
           }
           set.add(n);
           n = getNext(n);
        }
        return true ;

    }
    private int getNext(int n){
        int res = 0;
        while(n > 0){
            int temp = 0;
            temp = n%10;
            res += temp * temp;
             n = n/10;
            
        }
        return res;

    }
}

注意java运算符优先级,之前写的是 res += n%10 * n%10  因为 *和 %优先级一致,这会导致不符合预期的结果。

1.两数之和

public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    if(nums == null || nums.length == 0){
        return res;
    }
    Map<Integer, Integer> map = new HashMap<>();
    for(int i = 0; i < nums.length; i++){
        int temp = target - nums[i];   // 遍历当前元素,并在map中寻找是否有匹配的key
        if(map.containsKey(temp)){
            res[1] = i;
            res[0] = map.get(temp);
            break;
        }
        map.put(nums[i], i);    // 如果没找到匹配对,就把访问过的元素和下标加入到map中
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值