【问题标题】:How do I increase the algorithm performance for longer array of numbers?如何为更长的数字数组提高算法性能?
【发布时间】:2017-08-21 21:27:15
【问题描述】:

感谢收看。

计算有序数字数组中有多少个小于 4。

如何提高更长数组的算法性能?提高计算速度。二进制搜索有帮助吗?输出?

    public static int CountNumbers(int[] sortedArray, int lessThan)
    {
        int count = 0;

        for (int i = 0, len = sortedArray.Length; i < len; i++)
            if (sortedArray[i] < lessThan)
                count++;
            else return count;

        return count;
    }

Assert.AreEqual(SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4), 2);

【问题讨论】:

  • 使用二进制搜索
  • 当您尝试使用二分搜索时发生了什么?
  • @SergeyBerezovskiy:二进制搜索什么数字?
  • @Tigran O(n log(n)) 比 O(n) 更多,而不是更少。二分查找是 O(log(n))。
  • 如前所述,二分搜索是您的朋友。使用返回给定数组中搜索值位置的实现(如果我们插入此值)。

标签: c# .net algorithm sortedlist


【解决方案1】:

你应该使用Array.BinarySearch

static int CountNumbers(int[] sortedArray, int lessThan)
{
    if (sortedArray[0] >= lessThan) return 0;

    int lengthOfArray = sortedArray.Length;
    if (lengthOfArray == 0) return 0;
    if (sortedArray[lengthOfArray - 1] < lessThan) return lengthOfArray;

    int index = Array.BinarySearch(sortedArray, lessThan);
    if (index < 0)
        return ~index;
    // Find first occurrence in case of duplicate
    for (; index > 0 && sortedArray[index - 1] == lessThan; index--) ;
    return index;
}

【讨论】:

    【解决方案2】:

    解决此类问题的一个好方法是将数组拆分为更小的部分,并在ThreadPool(参见https://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx)的帮助下提高计算速度。

    【讨论】:

    • 二进制搜索实际上不可能实现多线程,因为执行的每个操作都取决于前一个操作的结果。您可以进行 n 元搜索,其中 n 是线程数加一,但单线程二分搜索非常快,并且 n -ary 搜索需要如此多的线程间通信,我无法想象线程在这里是有用的。
    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2022-12-11
    • 2018-01-08
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多