Day6 哈希表part01

Leetcode: 242 有效的字母异位词
class Solution {
    public boolean isAnagram(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        if(slen != tlen) return false;
        HashMap<Character, Integer> smap = new HashMap<Character, Integer>();
        for(int i = 0; i < slen; i++){
            char c = s.charAt(i);
            smap.put(c, smap.getOrDefault(c,0)+1);
        }
        for(int i = 0; i < tlen; i++){
            char c = t.charAt(i);
            int times = smap.getOrDefault(c,0);
            if(times == 0) return false;
            smap.put(c, smap.getOrDefault(c,0)-1);
        }
        return true;
    }
}
LeetCode: 349 两个数组的交集
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        ArrayList<Integer> output = new ArrayList<Integer>();
        HashSet<Integer> set1 = new HashSet<Integer>();
        HashSet<Integer> set2 = new HashSet<Integer>();
        for(int a: nums1){
            set1.add(a);
        }
        for(int a:nums2){
            set2.add(a);
        }
        for(Integer i: set2){
            boolean flag = set1.remove(i);
            if(flag) output.add(i);
        }
        int[] finaloutput = new int[output.size()];
        for(int i = 0; i < output.size(); i++){
            finaloutput[i] = output.get(i);
        }
        return finaloutput;
    }
}
LeetCode: 202 快乐数
class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> havefind = new HashSet<Integer>();
        while(!havefind.contains(n)){
            havefind.add(n);
            if(n == 1){
                return true;
            }
            System.out.println(n);
            n = powersum(n);
        }
        return false;
    }
    public int powersum(int n){
        int sum = 0;
        while(n / 10 != 0){
            sum += Math.pow(n % 10, 2);
            n /= 10;
        }
        sum += Math.pow(n, 2);
        return sum;
    } 
}
Leetcode: 1 两数之和
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> havefind = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> wantfind = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++){
            havefind.put(nums[i], i);
            if(wantfind.containsKey(nums[i]))
                return new int[]{i, wantfind.get(nums[i])};
            wantfind.put(target - nums[i], i);
        }
        return new int[]{0, 0};
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值