Leetcode刷题笔记1 哈希表part01

Leetcode242 有效的字母异位词

哈希法

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        array = [0] * 26
        for i in s:
            array[ord(i) - ord('a')] += 1
        for i in t:
            array[ord(i) - ord('a')] -= 1
        for i in range(26):
            if array[i] != 0:
                return False
        return True

字典法:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        dic = defaultdict(int)
        for i in s:
            dic[i] += 1
        for i in t:
            dic[i] -= 1
        for v in dic.values():
            if v != 0:
                return False
        return True

Leetcode349  两个数组的交集

字典和集合的结合使用

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)

直接集合:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1)&set(nums2))

Leetcode202 快乐数

求和的简单方法需要注意

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            digit = [int(i)**2 for i in str(n)]
            n = sum(digit)
        return n == 1

Leetcode1 两数之和

考察字典的运用,目前在哈希表的学习中我认为是对数组、集合、字典的理解与运用。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i, value in enumerate(nums):
            if target - value in dic:
                return [dic[target-value],i]
            dic[nums[i]] = i
        return []

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值