代码随想录day6

题目一:

使用数组构建哈希表

提取ASCII码:ord

不能用[[0] for _in range(26)]

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        record=[0]*26
        for i in s:
            record[ord(i)-ord("a")]+=1
        for j in t:
            record[ord(j)-ord("a")]-=1
        for n in record:
            if n !=0:
                return False
        return True

题目二

使用一个map,存储nums1,使用一个set提取相同元素

if num in table  与 if num in table.keys()相同

删除键值对 del table[num]

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        table={}
        for num in nums1:
            table[num]=table.get(num,0)+1
            # table[num]=1
        
        res=set()
        for num in nums2:
            if num in table.keys():
                res.add(num)
                del table[num]
        return list(res)

题目三

构建set,防止死循环出现即可。

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        res=set()
        while n not in res:
            res.add(n)
            nums=list(str(n))
            nums=[int(i)**2 for i in nums]
            n=sum(nums)
            if n==1:
                return True
        return False

题目四

在遍历到每个元素时,查看之前遍历的元素中有没有符合的元素

以数值为key,以索引为value

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        table={}
        i=0
        for num in nums:
            if (target-num) in table.keys():
                return [table[target-num],i]

            if num not in table:
                table[num]=i
            i+=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值