【问题标题】:Fastest algorithm to merge 2 arrays such that elements are interlocked at even intervals合并 2 个数组的最快算法,使元素以均匀的间隔互锁
【发布时间】:2015-03-04 15:33:33
【问题描述】:

要求:

  • 仅限整数运算(无浮点数)
  • 元素以尽可能均匀的间隔互锁

注意:

  • “尽可能均匀的间隔”可以定义为使每个间隔长度尽可能接近一个值。
  • 欢迎并希望进行微优化。

输入和输出示例:

//Inputs
[ 1, 2, 3, 4, 5, 6, 7 ]
[ 10, 20, 30, 40 ]

//Correct output
[ 1, 10, 2, 20, 3, 30, 4, 5, 40, 6, 7]

//Wrong output ([5, 6, 7] is not an optimal interval)
[ 1, 10, 2, 20, 3, 30, 4, 40, 5, 6, 7] 

-

//Inputs
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[ 2, 2, 2 ]

//Correct output
[ 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 3, 1, 1]

//Wrong output (last [1] is not an optimal interval)
[ 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1]

【问题讨论】:

  • 首先,选择一种语言。其次,自己尝试一些东西。第三,如果欢迎和期望微优化,那么您可能应该解释为什么以及是否要针对大小、内存使用或性能进行优化。或者重新考虑你的方法和Write Dumb Code
  • @ElliottFrisch 1st:好的。第二:我做了,但让我们假装这个问题仍然有效。 3rd:不,这是一般的优化请求,没有具体内容。
  • 任何good line drawing algorithm 都会这样做。
  • @user3386109 是的,我使用的是 Bresenham,但不确定这是否是最快的。我想我会发布我的答案,看看人们是否有更快的实现。

标签: c# algorithm optimization


【解决方案1】:

这是我自己的实现,对托管语言进行了尽可能多的优化。在 C++ 中,对数组指针使用三重异或交换可能会更快,但我不确定。可能需要查看 JITed 程序集以进一步优化此特定代码。

同时,让我们看看其他人是否有更好的算法。

int[] InterlockMerge(int[] a1, int[] a2) {
    var longSet = a1;
    var shortSet = a2;

    //Swap if a2 is longer
    if (a1.Length < a2.Length){
        longSet = a2;
        shortSet = a1;
    }

    var ll = longSet.Length;
    var ls = shortSet.Length;
    var totalLength = ll + ls;
    int[] res = new int[totalLength];                   //The resulting set

    int l = ll / (ls + 1);                              //Initial testing ratio (an int)
    int li = 0;                                         //index for longSet
    int si = 0;                                         //index for shortSet
    for (int i = 0; i < totalLength; i++) {
        if (l > 0) {
            res[i] = longSet[li++];
            l--;
            continue;
        }
        res[i] = shortSet[si++];
        l = (ll - li) / (ls - si + 1);                  //Recalculate the testing ratio
    }
    return res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2014-08-22
    • 2013-09-04
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多