129. Rehashing

Leave a comment

August 23, 2016 by oneOokay

这题基本上是考linked list, 没有什么其他特别的。

public ListNode[] rehashing(ListNode[] hashTable) {
// write your code here
if (hashTable == null || hashTable.length <= 0) {
return null;
}

int newLen = 2 * hashTable.length;
ListNode[] newHash = new ListNode[newLen];

for (int i = 0; i < hashTable.length; i ++) {
while (hashTable[i] != null) {
int newIndex = (hashTable[i].val % newLen + newLen) % newLen;
if (newHash[newIndex] == null) {
newHash[newIndex] = new ListNode(hashTable[i].val);
}else {
ListNode dummy = newHash[newIndex]; //使用dummy节点指针,以不影响newHash[i]
while (dummy.next != null) {
dummy = dummy.next;
}
dummy.next = new ListNode(hashTable[i].val);
}
hashTable[i] = hashTable[i].next; //不用存temporary,直接next
}
}
return newHash;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: