0817|代码随想录 哈希表系列 (一) python

#LC242 有效的字母异位词
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        record = [0]*26
        for word in s:
            record[ord(word) - ord("a")] += 1
        for word in t:
            record[ord(word) - ord("a")] -= 1

        for i in range(len(record)):
            if record[i] != 0:
                return False
        
        return True
##### 其他两种使用python默认collections库中实现的数据结构
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import defaultdict
        
        s_dict = defaultdict(int)
        t_dict = defaultdict(int)
        for x in s:
            s_dict[x] += 1
        
        for x in t:
            t_dict[x] += 1
        return s_dict == t_dict
 ####
class Solution(object):
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import Counter
        a_count = Counter(s)
        b_count = Counter(t)
        return a_count == b_count

数组就是一个简单的哈希表,本题中至多只有26个不同元素,那么索引就是数组的默认索引而其中的元素便是各个字母出现的次数。同时还可以使用两种collections库中内置的函数实现(这两种方式更像是使用字典)。

##LC349 两个数组的交集
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table = {}
        for num in nums1:
            table[num] = table.get(num, 0) + 1
        
        # 使用集合存储结果
        res = set()
        for num in nums2:
            if num in table:
                res.add(num)
                del table[num]
        
    return list(res)
### 使用set()直接对两个列表进行比对
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

直接使用python内部自带set很容易解决,同时还可以使用dict也就是{}字典来实现,但是要注意字典的无初值赋值操作以及删除操作。

##LC 202. 快乐数
class Solution:
    def isHappy(self, n: int) -> bool:
        record = set()
        while n not in record:
            record.add(n)
            new_num = 0
            n = str(n)
            for i in n:
                new_num += int(i)**2
            if new_num  == 1 :
                return True
            else: n = new_num
        return False
##### 第二种方法更多是对于数值计算的考量 ,其中的divmod函数是使用的关键。
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: int) -> int: 
        new_num = 0
        while n:
            n, r = divmod(n, 10)
            new_num += r ** 2
        return new_num

看似很复杂,实则是对终止条件的判断,由于无限循环的存在,大胆判断终止条件为new_num的复现,所以使用set来存储中间过程。

##LC1 两数之和
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = dict()

        for index,num in enumerate(nums):
            if target-num in records:
                return [records[target-num],index]
            records[num] = index
        
        return False

使用dict的特性,将数值作为索引,将在原列表中的位置作为对应值填入字典之中,根据对索引的查询完成位置定位。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = set()
        for i,num in enumerate(nums):
            complement = target-num
            if complement in seen:
                return [nums.index(complement),i]
            seen.add(num)

可以使用集合来存储数字,使用index方法来实现对于位置的索引,总结就是空间换时间。要去了解python中列表、集合、字典的实现方式,暂时猜测和哈希表有关(?),比如index函数的使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值