首页 > 代码库 > [LintCode] Rehashing
[LintCode] Rehashing
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; } };
[LintCode] Rehashing
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。