题目地址:
https://www.lintcode.com/problem/rehashing/description
重哈希。这里的Rehashing会使得新的哈希表的数组长度变为原来的两倍。哈希函数直接取的是数值模上数组长度。需要注意的是,这个题目的判定里要求,在重哈希的时候,添加ListNode的时候必须在链表尾部插入。代码如下:
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
int newCapacity = hashTable.length * 2;
ListNode[] res = new ListNode[newCapacity];
for (int i = 0; i < hashTable.length; i++) {
if (hashTable[i] != null) {
ListNode head = hashTable[i];
while (head != null) {
insert(res, head.val);
head = head.next;
}
}
}
return res;
}
private void insert(ListNode[] hashTable, int val) {
// 算一下重哈希后该值要放在哪个bucket下
// 需要注意的是,模运算在java里会产生负数,所以要加上数组长度再取模
int pos = (val + hashTable.length) % hashTable.length;
if (hashTable[pos] == null) {
hashTable[pos] = new ListNode(val);
} else {
ListNode head = hashTable[pos];
while (head.next != null) {
head = head.next;
}
head.next = new ListNode(val);
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n)。