【问题标题】:Merging two arraylists without creating third one合并两个数组列表而不创建第三个
【发布时间】:2016-04-28 08:46:59
【问题描述】:

这是一项任务,我正试图解决。你必须写函数

void merge(ArrayList a, ArrayList b)  {
// code
}

函数接收两个大小相等的 ArrayList 作为输入参数 [a1, a2, ..., an], [b1, b2, ..., bn]。 执行结果是第一个ArrayList必须包含两个列表的元素,并且它们交替一致([a1, b1, a2, b2, ..., an, bn]) 请阅读粗体字两次=)

代码必须尽可能高效地工作。

这是我的解决方案

public static void merge(ArrayList a, ArrayList b) {
ArrayList result = new ArrayList();
int i = 0;

Iterator iter1 = a.iterator();
Iterator iter2 = b.iterator();
while ((iter1.hasNext() || iter2.hasNext()) && i < (a.size() + b.size())) {
    if (i % 2 ==0) {
        result.add(iter1.next());
    } else {
        result.add(iter2.next());
    }
    i++;
}

a = result;

}

我知道它一点也不完美。但我不明白如何在不创建 tmp 列表的情况下合并到第一个列表中。

提前感谢您的参与。

【问题讨论】:

标签: arrays list merge


【解决方案1】:

最后我得到了这个:

public static void merge(ArrayList<Integer> arr1, ArrayList<Integer> arr2) {
        int indexForArr1 = arr1.size() - 1;
        int oldSize = arr1.size();
        int newSize = arr1.size() + arr2.size();

        /*
            decided not to create new arraylist with new size but just to fill up old one with nulls
         */
        fillWithNulls(arr1, newSize);

        for(int i = (newSize-1); i >= 0; i--) {
            if (i%2 != 0) {
                int indexForArr2 = i%oldSize;
                arr1.set(i,arr2.get(indexForArr2));
                oldSize--; // we reduce the size because we don't need tha last element any more
            } else {
                arr1.set(i, arr1.get(indexForArr1));
                indexForArr1--;
            }
        }
    }

    private static void fillWithNulls(ArrayList<Integer> array, int newSize) {
        int delta = newSize - array.size();
        for(int i = 0; i < delta; i++) {
            array.add(null);
        }
    }

再次感谢约翰的好主意!

【讨论】:

  • for 循环中使用oldSize - 1 并在每次迭代中设置i * 2i * 2 + 1 的元素会更有效一些。你会以这种方式摆脱两个%s 和if。并使用ArrayList.ensureCapacity 有效地为更大的arr1 分配内存。
  • 我稍后会尝试替换 oldsize var ArrayList.ensureCapacity 很明显,再次)
  • 直到现在我才想起 List 集合中的 put(index, object) 方法
【解决方案2】:

双 ArrayList a 的大小。将a 的最后两个元素设置为旧a 的最后一个元素和b 的最后一个元素。继续前进,每次都备份,直到到达 ab 的开头。您必须从后面进行,否则您将覆盖原来的 a 的值。

【讨论】:

  • 谢谢,约翰!解决方案就是这么简单!一如既往。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
相关资源
最近更新 更多