zoukankan      html  css  js  c++  java
  • lintcode-129-重哈希

    129-重哈希

    哈希表容量的大小在一开始是不确定的。如果哈希表存储的元素太多(如超过容量的十分之一),我们应该将哈希表容量扩大一倍,并将所有的哈希值重新安排。假设你有如下一哈希表:

    size=3, capacity=4

    [null, 21, 14, null]
    ↓ ↓
    9 null

    null
    哈希函数为:

    int hashcode(int key, int capacity) {
    return key % capacity;
    }
    这里有三个数字9,14,21,其中21和9共享同一个位置因为它们有相同的哈希值1(21 % 4 = 9 % 4 = 1)。我们将它们存储在同> 一个链表中。

    重建哈希表,将容量扩大一倍,我们将会得到:

    size=3, capacity=8
    index: 0 1 2 3 4 5 6 7
    hash : [null, 9, null, null, null, 21, 14, null]
    给定一个哈希表,返回重哈希后的哈希表。

    注意事项
    哈希表中负整数的下标位置可以通过下列方式计算:

    • C++/Java:如果你直接计算-4 % 3,你会得到-1,你可以应用函数:a % b = (a % b + b) % b得到一个非负整数。
    • Python:你可以直接用-1 % 3,你可以自动得到2。

    样例
    给出 [null, 21->9->null, 14->null, null]
    返回 [null, 9->null, null, null, null, 21->null, 14->null, null]

    标签
    LintCode 版权所有 哈希表

    思路

    根据原哈希表的值,建立新的哈希表即可

    code

    /**
     * Definition of ListNode
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *         this->val = val;
     *         this->next = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @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
         */    
        vector<ListNode*> rehashing(vector<ListNode*> hashTable) {
            // write your code here
            int capacity = hashTable.size();
            if (capacity <= 0) {
                return vector<ListNode*>();
            }
    
            vector<int> hashValue;
            for (ListNode *node : hashTable) {
                while (node != NULL) {
                    hashValue.push_back(node->val);
                    node = node->next;
                }
            }
    
            hashTable.clear();
            capacity *= 2;
            hashTable.resize(capacity);
    
            for (int i = 0; i < hashValue.size(); i++) {
                int index = (hashValue[i] % capacity + capacity) % capacity;
                if (hashTable[index] == NULL) {
                    hashTable[index] = new ListNode(hashValue[i]);
                }
                else {
                    ListNode* node = hashTable[index];
                    while (node->next != NULL) {
                        node = node->next;
                    }
                    node->next = new ListNode(hashValue[i]);
                }
            }
            return hashTable;
        }
    };
    
  • 相关阅读:
    jQuery图片翻转弹出动画特效
    HTML5来了,7个混合式移动开发框架
    10款很好用的 jQuery 图片滚动插件
    JS图片自动和可控的轮播切换特效
    CSS3扇形动画菜单 鼠标滑过扇形展开动画
    css里面的几个你不知道的属性
    JS判断是否是微信打开页面
    js的escape()、encodeURI()、encodeURIComponent()区别详解
    使用HTML5的十大原因
    Hybrid App开发 四大主流移平台分析
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7413047.html
Copyright © 2011-2022 走看看