力扣算法学习day04-1

力扣算法学习day04-1

242-有效的字母异位词

题目

image-20220124104816364

代码实现

class Solution {
    public boolean isAnagram(String s, String t) {
        // 代表26个英文字母
        int[] temp = new int[26];

        // 然后,需要对比两个字符串每个字母的出现频率之差。
        for(char sChar : s.toCharArray()){
            temp[sChar - 'a']++;
        }

        for(char tChar : t.toCharArray()){
            temp[tChar - 'a']--;
        }

        // 如果是字母异位词,那么整个数组应该都为0
        for(int i = 0;i < temp.length;i++){
            if(temp[i] != 0){
                return false;
            }
        }
        return true;
    }
}

349-两个数组的交集

题目

image-20220124121828954

代码实现

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // 这道题不需要,但是严谨上说,可以加上。
        if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
            return new int[0];
        }

        HashSet<Integer> set1 = new HashSet();
        HashSet<Integer> set2 = new HashSet();

        // 首先,将nums1中的出现的数放入set1中
        for(int i = 0;i < nums1.length;i++){
            set1.add(nums1[i]);
        }

        // 然后,判断nums2中的数是否有与num1中相同的,有则放入set2中
        for(int j = 0;j < nums2.length;j++){
            if(set1.contains(nums2[j])){
                set2.add(nums2[j]);
            }
        }

        // 经过上面的过程后,set2中存储的就是交集元素了。
        int[] temp = new int[set2.size()];
        int index = 0;

        // 将元素取出,装入数组。
        for(int i : set2){
            temp[index++] =i;
        }
        
        return temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

人山人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值