DAY06——哈希表

1

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

2.

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for(int i: nums1){
            set1.add(i);
        }
        for(int i: nums2){
            if(set1.contains(i)){
                set2.add(i);
            }
        }

        // int[] arr = new int[set2.size()];
        // int j = 0;
        // for(int i : set2){
        //     arr[j++] = i;
        // }
        // return arr;
        return set2.stream().mapToInt(x -> x).toArray();

    }
}

3.

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> store = new HashSet<>();
        while(n!=1 && !store.contains(n)){
            store.add(n);
            n = computeSum(n);
        }
        return n==1;
    }
    private int computeSum(int num){
        int sum = 0;
        while(num>0){
            int a = num % 10;
            int b = a * a;
            sum = sum + b;
            num = num / 10;
        }
        //System.out.println(sum);
        return sum;
    
    }
}

4

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}
//Hash索引表示 eg.[2,7,11,15] target=9
//2,0
//7,1
//11,2
//15,3   只需遍历一遍数组

//循环法:将两个数字返回数组写法  return new int[]{i, j};  

//最终返回空数组 return new int[0];  
//本身的含义是长度为0的空数组:返回一个垃圾值,是为了防止编译器报错

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值