Rehashing
Code
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) {
int capacity = hashTable.length * 2;
ListNode[] newTable = new ListNode[capacity];
for (int i = 0; i < hashTable.length; i++) {
ListNode node = hashTable[i];
while(node != null) {
int index = hash(node.val, capacity);
ListNode rnode = newTable[index];
if (rnode == null) {
newTable[index] = new ListNode(node.val);
} else {
ListNode newNode = new ListNode(node.val);
while (rnode.next != null) {
rnode = rnode.next;
}
rnode.next = newNode;
}
node = node.next;
}
}
return newTable;
}
private int hash(int key, int capacity) {
return (key % capacity + capacity) % capacity;
}
};Analysis
Last updated