哈希表 part 1

相关阅读:https://docs.qq.com/doc/DUEtFSGdreWRuR2p4

当遇到了要快速判断一个元素是否出现集合里的时候,就需要考虑哈希法。

1. 两数之和

def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {} 
        #x 为当前数字 j 为下标
        for j, x in enumerate(nums) :
            #target - x 为当前的数字与target的差
            if target - x in d :
                #返回字典中target-x的位置和当前x的下标j 
                return [d[target-x], j]
            else: 
                #如果差值不存在当前字典中,将j存入字典的value中
                d[x] = j 

242: 

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        d = {} 
        for item in s: 
            if item in d: 
                d[item] += 1 
            else: 
                d[item] = 1 
            
        d1 = {} 
        for item in t: 
            if item in d1: 
                d1[item] += 1 
            else:
                d1[item] = 1
        
        if d == d1 :
            return True
        else: 
            return False

349: 

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        d={} 
        for i in nums1:
            if i not in d:
                d[i] = 1 
        res=set() 
        for num in nums2:
            if num in d:
                res.add(num) 
                
        return list(res)

202.

#建立一个集合,用来装已经算过的数,然后一个循环:
#如果 n == 1 return true 
#else: n在集合中出现过,说明进入死循环, return false 
#and 将n 放入集合中,进入下一次循环 
def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        record = set() 
        while n not in record :
            record.add(n) 
            new_num = 0 
            n_str = str(n) 
            for in n_str:
                new_num += int(i)**2 
            
            if new_num == 1 :
                return True 
            else: 
                n = new_num
        
        return False 

 

posted @ 2023-08-25 13:43  大蟒蛇进动吐痰  阅读(14)  评论(0)    收藏  举报