代码随想录算法训练营第5天 | 242.有效的字母异位词 / 349. 两个数组的交集 / 202. 快乐数 / 1. 两数之和

242. 有效的字母异位词

方法1(哈希表):将字符编码为字母表顺序并计数

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        record = [0] * 26
        for i in s:
            #并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
            record[ord(i) - ord("a")] += 1
        for i in t:
            record[ord(i) - ord("a")] -= 1
        for i in range(26):
            if record[i] != 0:
                #record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
                return False
        return True

方法2:defaultdict

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import defaultdict
        s_dict = defaultdict(int)
        t_dict = defaultdict(int)

        for i in s:
            s_dict[i] += 1
        for i in t:
            t_dict[i] += 1
        
        return True if s_dict == t_dict else False
       

方法 3:Counter

  • Counter的效果:返回一个字典 {字母:频次}

>>> from collections import Counter 
>>> s = 'avdas'
>>> s_cnt = Counter(s)
>>> s_cnt
Counter({'a': 2, 'v': 1, 'd': 1, 's': 1})
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import Counter
        s_cnt = Counter(s)
        t_cnt = Counter(t)
        return True if s_cnt == t_cnt else False

349. 两个数组的交集

方法1:暴力解

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        for item in nums1:
            if item in nums2:
                res.append(item)
        return list(set(res))

方法2:字典+数组

  1. 通过将nums1通过哈希变换(即转化为字典table {字母:频次}),则table中不包含重复的量;
  2. 剩下的部分和暴力解相同,即遍历。
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table = {}
        # 创建一个哈希表为字典
        for i in nums1:
            table[i] = table.get(i, 0) + 1
        res = set()
        for i in nums2:
            if i in table:
                res.add(i)
                del table[i]
        return list(res)

方法3 :数组

  1. 将nums1和nums2都转化为下标为元素,值为频次的数组;
  2. 剩下的部分则遍历;
    缺点:只有数组可用,且在已知数组的最大长度时才可用;浪费内存。
  class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count1 = [0]*1001
        count2 = [0]*1001
        result = []
        for i in range(len(nums1)):
            count1[nums1[i]]+=1
        for j in range(len(nums2)):
            count2[nums2[j]]+=1
        for k in range(1001):
            if count1[k]*count2[k]>0:
                result.append(k)
        return result

方法4:集合

采用 & 求解set的交集

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # 采用&求解两个set的交集
        return list(set(nums1) & set(nums2))

202.快乐数

  • 快乐数即每位平方之和(迭代)为1;
  • 非快乐数即每位平方之和(迭代)永不为1,即每位平方之和可能出现重复;
  • 哈希表思路:当出现过的和又出现时,不为快乐数,否则当和为1是为快乐数;即判断当出现过的和,是否出现在之前出现的和的集合中

方法1:集合

class Solution:
    def isHappy(self, n: int) -> bool:        
        record = set()
        while True:
            n = self.get_sum(n)
            if n == 1:
                return True
            if n in record:
                return False
            else:
                record.add(n)
    # 求解每一位的平方    
    def get_sum(self, n):
        sum = 0
        while n:
            n, r = divmod(n, 10)   # n/10 获得商为n, 余数为r
            sum += r ** 2
        return sum

方法2:集合+字符化数字

核心思路:将数字先转化为字符串,随后即可通过in命令逐个取出字符串,转化为int类型后即可进行平方运算。

class Solution:
    def isHappy(self, n: int) -> bool:  
        record = set()      
        while n not in record:
            record.add(n)
            n_str = str(n)
            new_sum = 0
            for i in n_str:
                new_sum += int(i) ** 2
            if new_sum == 1:
                return True
            if new_sum in record:
                return False
            else:
                n = new_sum

1.两数之和

方法1:字典

哈希表思路:将nums变换为一个“值:下标”的字典,遍历nums,查看target-nums[i]是否在字典中。

  • 注意:
    (1)由于在nums中采用遍历的方法,nums从头到尾一遍过,因此不会存在取到相同下标的情况;
    (2)假设target-nums[i]不在字典中,则把遍历过的数据放到字典中。
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {} # 值:下标
        for i in range(len(nums)):
            need = target - nums[i]
            if need in map.keys():
                return [i, map[need]]
            else:
                map[nums[i]] = i
        return []
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值