代码随想录DAY06

哈希表

用于快速判断一个元素是否存在于集合里。以空间换取时间。

有一个哈希函数,会出现哈希碰撞。

哈希碰撞的解决办法:拉链法,线性探测法。

常见的三种哈希结构:数组,集合,映射。

有效的字母异位词

ord()函数为字符对应的ASCII数值。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        hash = [0]*26
        for i in s:
            hash[ord(i) -ord('a')] += 1

        for j in t:
            hash[ord(j) - ord('a')] -= 1
        for i in range(26):
            if hash[i]!=0:
                return False
        return True

求两个数组的交集

 class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        dic = {}
        for i in nums1:
            dic[i] = 1
        for j in nums2:
            if j in dic and j not in res:
                res.append(j)
        return res

快乐数

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        res = []
        while True:
            n = self.sum(n)
            if n == 1:
                return True
            if n not in res:
                res.append(n)

            else:
                return False
    def sum(self,n):
        sum = 0
        while n:
            n,r = divmod(n,10)
            sum += r**2
        return sum

两个数之和

enumerate()是获取数组元素的下标及值。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        seen = []
        for i,num,in enumerate(nums):
            rest = target-num
            if rest in seen:
                return [nums.index(rest),i]
            seen.append(num)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值