【问题标题】:Looking for efficient method to extract elements of hash table into a single array寻找将哈希表的元素提取到单个数组中的有效方法
【发布时间】:2023-04-02 11:24:01
【问题描述】:

我创建了自己的哈希表实现,其中链表存储在数组的每个条目中(大小为 11)。我正在尝试将哈希表的元素提取到单个数组中,然后对元素数组进行排序。我想过简单地将每个链表提取到结果数组中,然后再对数组进行排序。如下方法所示

//turns the whole hash table into an array
    private int[] toArray() {
        int sizeOfArray = 0;
        for(int i=0; i<11; i++)
        {
            //calculate the total number of elements in the hashTable
            sizeOfArray += hashMap.getList(i).size();
        }

        int[] result = new int[sizeOfArray];

        int indexRes = 0;
        //import every entry from the hash table into a single array
        for(int i=0; i<11; i++)
        {
            KeyValuePairLinkedList list = hashMap.getList(i);

            //convert the list to an array
            int[] listArray = list.toArray();
            for(int j=0; j<list.size(); j++)
            {
                result[indexRes] = listArray[j];
                indexRes++;
            }
        }
        return result;
    }

但是如果每个链表中的元素已经排序,那么我可以将元素合并到一个数组中,类似于合并排序算法合并两个数组的方式,但是我将合并 11 个数组,而不仅仅是 2 个和我猜这需要很多代码。

另外,假设我只想提取存储在哈希表中的偶数整数,然后在结果数组中对这些整数进行排序。我可以再次使用相同的方法,将整个哈希表提取到一个数组中,然后删除奇数,然后排序。但是必须有更好的方法来做到这一点。

【问题讨论】:

  • 每个链表的平均大小是多少?如果它们很小,那么合并它们并没有什么好处。
  • 看看这里关于 N 路合并的一些想法:stackoverflow.com/questions/5055909/algorithm-for-n-way-merge
  • 如果数组大小为 11,那么列表的平均大小一定非常小。在我看来,这是一个过度优化。运行测试看看你是否需要如此复杂的优化。

标签: java performance linked-list hashtable mergesort


【解决方案1】:

一种方法,如果数组已经排序

  • 为每个数组中的第一个元素构建一个最小堆
  • 选择最小值,放入最终数组+提取下一个元素并插入堆中

继续这样做,直到用尽所有阵列。 堆中的每个元素都有值 + 指向哪个数组的指针,以及它是什么索引。

注意特殊情况,其中一个数组用完,不再需要插入堆中。

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2012-08-05
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多