标签:interview
http://lintcode.com/en/problem/rehashing/#
/**
* 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 the total size of keys is too large (e.g. size >= capacity / 10),
// we should double the size of the hash table and rehash every keys.
//
// This is load factor
if (hashTable == null)
return null;
int originalSize = hashTable.length;
int newSize = originalSize * 2;
ListNode[] heads = new ListNode[newSize];
ListNode[] tails = new ListNode[newSize];
for (ListNode n : hashTable)
{
while (n != null)
{
int i = calcIndex(newSize, n.val);
if (heads[i] == null)
{
heads[i] = n;
tails[i] = n;
}
else
{
tails[i].next = n;
tails[i] = n;
}
// NOTE
// Disconnent previous
ListNode next = n.next;
n.next = null;
n = next;
}
}
return heads;
}
private int calcIndex(int size, int input)
{
if (input >= 0)
return input % size;
else
return (input % size + size ) % size;
}
};标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1603933