代码随想录算法训练营Day06-哈希表01

212.有效的字母异位词

如果两个字符串互为字母异位词那长度一定相同,然后遍历;两个字符串,每个字母的出现次数相同即为字母异位词,所以我们需新建一个长度26的数组来记录每个字母增减次数,遍历结束该数组所以元素均为零就符合条件。可以通过ASCII相对值s[i]-'a'映射数组0-25索引值,具体如下:

public class Solution {
        public bool IsAnagram(string s, string t) {
            int sl=s.Length,tl=t.Length;
            if(sl!=tl) return false;
            int[] a = new int[26];
            for(int i = 0; i < sl; i++){
                a[s[i] - 'a']++;
                a[t[i] - 'a']--;
            }       
            foreach (int i in a)//遍历新数组,确保所有元素均不为0
            {
                if (i != 0)
                    return false;
            }
            return true;
        }
    }

 349. 两个数组的交集

该题利用了HashSet的不重复性

public class Solution {
        public int[] Intersection(int[] nums1, int[] nums2) {
            if(nums1==null||nums1.Length==0||nums2==null||nums1.Length==0)
                return new int[0]; //注意数组条件
            HashSet<int> one = Insert(nums1);//调用函数添加nums1元素到one集合
            HashSet<int> two = Insert(nums2);
            one.IntersectWith(two);//使用HashSet的交集方法
            return one.ToArray();
        }
        public HashSet<int> Insert(int[] nums){
            HashSet<int> one = new HashSet<int>();
            foreach(int num in nums){
                one.Add(num);         
            }
            return one;
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

cyn620

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

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

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

打赏作者

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

抵扣说明:

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

余额充值