Problem
The size of the hash table is not determinate at the very beginning. 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. Say you have a hash table looks like below:
size=3, capacity=4 [null, 21, 14, null] ↓ ↓ 9 null ↓ null
The hash function is:
int hashcode(int key, int capacity) {
return key % capacity;
}
here we have three numbers, 9, 14 and 21, where 21 and 9 share the same position as they all have the same hashcode 1 (21 % 4 = 9 % 4 = 1). We store them in the hash table by linked list.
rehashing this hash table, double the capacity, you will get:
size=3, capacity=8 index: 0 1 2 3 4 5 6 7 hash : [null, 9, null, null, null, 21, 14, null]
Given the original hash table, return the new hash table after rehashing .
NoticeFor negative integer in hash table, the position can be calculated as follow:
C++/Java: if you directly calculate -4 % 3 you will get -1. You can use function: a % b = (a % b + b) % b to make it is a non negative integer.
Python: you can directly use -1 % 3, you will get 2 automatically.
Given [null, 21->9->null, 14->null, null],
return [null, 9->null, null, null, null, 21->null, 14->null, null]
Note Solutionpublic class Solution { public ListNode[] rehashing(ListNode[] hashTable) { if (hashTable == null || hashTable.length == 0) return hashTable; int cap = hashTable.length*2; ListNode[] res = new ListNode[cap]; ListNode[] temp = new ListNode[cap]; for (int i = 0; i < cap/2; i++) { ListNode cur = hashTable[i]; while (cur != null) { ListNode node = new ListNode(cur.val); hashTable[i] = cur.next; int index = (cur.val%cap + cap)%cap; if (res[index] == null) { res[index] = node; temp[index] = node; } else { temp[index].next = node; temp[index] = node; } cur = cur.next; } } return res; } };
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65747.html
摘要:剑指最小栈声明文章均为本人技术笔记,转载请注明出处解题思路实现功能实现一个最小栈,要求操作均为复杂度,解题思路用栈存储数据用最小栈存储中最小元素,保证栈顶元素与栈顶元素同步,表示此时最小值将与此时最小值比较,将更小的一方压栈,保证中栈顶始终 剑指offer/LintCode12_最小栈 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault.com/u/yz...
摘要:剑指用两个栈模拟队列声明文章均为本人技术笔记,转载请注明出处解题思路实现功能用两个栈模拟实现一个队列的,和操作解题思路假设有两个栈队列实现始终用入栈实现队列和实现由于依次出栈并压入中,恰好保证中顺序与模拟队列顺序一致,始终保证栈顶元素为模拟 剑指offer/LintCode40_用两个栈模拟队列 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault.com...
摘要:剑指用两个队列实现一个栈声明文章均为本人技术笔记,转载请注明出处解题思路实现功能用两个队列实现一个栈,实现,,和方法解题思路假设有队列和实现栈的操作实现栈操作始终用来入队实现实现栈的方法模拟栈的过程中,保证两个队列中始终有一个队列为空,另一 剑指offer/LintCode494_用两个队列实现一个栈 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault....
摘要:剑指缓存实现声明文章均为本人技术笔记,转载请注明出处解题思路缓存两种功能获取的对应,不存在返回版本版本设置缓存已满,删除最近最久未被使用的节点,添加新节点进缓存缓存未满,节点存在,修改节点不存在,添加新节点进缓存解题思路由于缓存插入和删除 剑指offer/LeetCode146/LintCode134_LRU缓存实现 声明 文章均为本人技术笔记,转载请注明出处[1] https://s...
阅读 2807·2021-09-28 09:45
阅读 1491·2021-09-26 10:13
阅读 885·2021-09-04 16:45
阅读 3615·2021-08-18 10:21
阅读 1066·2019-08-29 15:07
阅读 2615·2019-08-29 14:10
阅读 3129·2019-08-29 13:02
阅读 2449·2019-08-29 12:31