/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public 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
*/
public ListNode[] rehashing(ListNode[] hashTable) {
// write your code here
if(hashTable.length==0){
return null;
}
int newcap=2*hashTable.length;//rehashing需要两倍的空间
ListNode[] newtable=new ListNode[newcap];//建立新表
for(int i=0;i<hashTable.length;i++){
while(hashTable[i]!=null){
//rehashing时需要重新计算key的位置
int newindex = (hashTable[i].val%newcap+newcap)%newcap;
//如果这个位置没有被占用
if(newtable[newindex]==null){
newtable[newindex]=new ListNode(hashTable[i].val);
}
//如果有这个位置已有
else{
ListNode dummy=newtable[newindex];
while(dummy.next!=null){
dummy=dummy.next;
}
dummy.next=new ListNode(hashTable[i].val);
}
//转移下一个点
hashTable[i]=hashTable[i].next;
}
}
return newtable;
}
};
129. Rehashing(当hashtable不够时需要扩容)
最新推荐文章于 2022-05-08 23:10:52 发布