python--lintcode129. 重哈希

描述

哈希表容量的大小在一开始是不确定的。如果哈希表存储的元素太多(如超过容量的十分之一),我们应该将哈希表容量扩大一倍,并将所有的哈希值重新安排。假设你有如下一哈希表:

size=3, capacity=4

[null, 21, 14, null]
       ↓    ↓
       9   null
       ↓
      null

哈希函数为:

int hashcode(int key, int capacity) {
    return key % capacity;
}

这里有三个数字9,14,21,其中21和9共享同一个位置因为它们有相同的哈希值1(21 % 4 = 9 % 4 = 1)。我们将它们存储在同一个链表中。

重建哈希表,将容量扩大一倍,我们将会得到:

size=3, capacity=8

index:   0    1    2    3     4    5    6   7
hash : [null, 9, null, null, null, 21, 14, null]

给定一个哈希表,返回重哈希后的哈希表。

哈希表中负整数的下标位置可以通过下列方式计算:

  • C++/Java:如果你直接计算-4 % 3,你会得到-1,你可以应用函数:a % b = (a % b + b) % b得到一个非负整数。
  • Python:你可以直接用-1 % 3,你可以自动得到2

这一题好像没什么可讲的,就是链表的操作吧,套着个哈希表的外衣。

直接看代码:

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next

class Solution:
    """
    @param hashTable: A list of The first node of linked list
    @return: A list of The first node of linked list which have twice size
    """
    def rehashing(self, hashTable):
        # write your code here
        def insert(hash,node):
            index=node.val%len(hash)
            if(hash[index]==None):
                nodenew=ListNode(node.val)
                hash[index]=nodenew
            else:
                head=hash[index]
                while(head.next!=None):
                    head=head.next
                nodenew = ListNode(node.val)
                head.next=nodenew


        length=len(hashTable)*2
        result=[]
        for i in range(length):
            result.append(None)
        for i in range(len(hashTable)):
            if(hashTable[i]==None):continue
            else:
                node=hashTable[i]
                insert(result,node)
                while(node.next!=None):
                    node=node.next
                    insert(result,node)
        return result






node0=ListNode(0)
node4=ListNode(4)
node8=ListNode(8)
node0.next=node4
node4.next=node8

node1=ListNode(1)
node5=ListNode(5)
node1.next=node5


s = Solution()
result = s.rehashing([node0,node1,None,None])

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值