算法学习Day4——哈希1

在需要判断元素是否重复出现的时候可以考虑使用哈希法。

242 有效的字母异位词

242. 有效的字母异位词 - 力扣(LeetCode)

使用数组

核心:使用一个26大小的数组记录每个字母出现的次数,第一次++,第二次--,最后看数组是否全部为0。

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 i=0;i<t.length();i++){
            record[t.charAt(i) - 'a']--;
        }
        for(int count:record){
            if(count!=0){
                return false;
            }
        }
        return true;

    }
}

349 两个数组的交集

349. 两个数组的交集 - 力扣(LeetCode)

由于没有限制数值大小,所以不用数组来做哈希表,使用hashset

最后结果输出有两种方式:1.转化成数组。 2.重新申请一个数组来存放。

import java.util.HashSet;
import java.util.Set;
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1= new HashSet<>();
        Set<Integer> resSet=new HashSet<>();
        for(int i:nums1){
            set1.add(i);
        }
        for(int i:nums2){
            if(set1.contains(i)){
                resSet.add(i);
            }
        }
        return resSet.stream().mapToInt(x->x).toArray();

    }
}

202 快乐数

202. 快乐数 - 力扣(LeetCode)

关键是看sum和会不会重复出现。还有就是求每个数字的平方和的操作。

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record= new HashSet<>();
        while(n!=1 && !record.contains(n)){
            record.add(n);
            n=getNextNumber(n);
        }
        return n==1;

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

两数之和

1. 两数之和 - 力扣(LeetCode)

使用map

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res =new int[2];
        Map<Integer,Integer> map =new HashMap<>();
        for(int i=0;i<nums.length;i++){
//找map里面有没有存符合的
            int temp=target-nums[i];
            if(map.containsKey(temp)){
                res[1]=i;
                res[0]=map.get(temp);
                break;
            }
            map.put(nums[i],i); //如果没有就存进去
        }
        return res;

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

endless_?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值