刷题:散列表—哈希表

哈希表

原理示意图:

 哈希函数:

 

哈希函数的方法

直接定址法

适用于连续数据:

 

 除留余数法

平方取中法

基数转换法

 哈希冲突

开放地址法

 

 

 

 

 链地址法

 

 

 

 

例子

存在重复元素

 

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
       if len(list(set(nums))) == len(nums):
           return False
       else:
            return True
 
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        numDict = dict()
        for num in nums:
            if num in numDict:
                return True
            else:
                numDict[num] = num
        return False

有效的数独

 

 

 为每个小方块进行编号

 

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        rows_map = [dict() for _ in range(9)]
        cols_map = [dict() for _ in range(9)]
        boxes_map = [dict() for _ in range(9)]
        for i in range(9):
            for j in range(9):
                if board[i][j] == '.':
                    continue
                #获取数独上的数字
                num = int(board[i][j])
                #当前方格处在哪个九宫格之中
                box_index = (i//3)*3+j//3
                
                row_num = rows_map[i].get(num,0)
                col_num = cols_map[j].get(num,0)
                box_num = boxes_map[box_index].get(num,0)
                if row_num > 0 or col_num >0 or box_num >0:
                    return False
                rows_map[i][num] = 1
                cols_map[j][num] = 1
                boxes_map[box_index][num] = 1
        return True

任务

存在重复元素Ⅱ

超时

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        for i in range(len(nums)):
            for j in range(len(nums)):
                if i != j and nums[i] == nums[j] and abs(i-j) <= k:
                    return True
        return False

 哈希方法

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        pos = {}
        for i, num in enumerate(nums):
            if num in pos and i - pos[num] <= k:
                return True
            pos[num] = i
        return False

宝石与石头

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        bucket = dict()
        #print(bucket)

        for stone in stones:
            bucket[stone] = bucket.get(stone, 0) + 1
            
        
        return sum([bucket.get(jewel, 0) for jewel in jewels])


class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        n = 0
        for i in stones:
            if i in jewels:
                n += 1
        return n

子域名访问计数

class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        all = []
        father = {}
        for i in range(len(cpdomains)):
            a= cpdomains[i].split()
            num = int(a[0])
            son = a[1].split('.')
            son_list = []
            for j in range(len(son)):
                son_list.append(son[j:len(son)])
            for m in son_list:
                #c = num +' '+ '.'.join(m)
                c = '.'.join(m)

                if c in father.keys():
                    father[c] = int(father.get(c)) + int(num)
                else:
                    father[c] = num
        for k,v in father.items():
            b = str(v)+' ' + k
            all.append(b)
        return all

 

class Solution(object):
    def subdomainVisits(self, cpdomains):
        ans = collections.Counter()
        for domain in cpdomains:
            count, domain = domain.split()
            count = int(count)
            frags = domain.split('.')
            for i in xrange(len(frags)):
                ans[".".join(frags[i:])] += count

        return ["{} {}".format(ct, dom) for dom, ct in ans.items()]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值