c# - 如何加快循环百万值数组的过程?

标签 c# arrays loops

所以我进行了一个在线测试,我必须实现一段代码来简单地检查值是否在数组中。我写了下面的代码:

    using System;
    using System.IO;
    using System.Linq;

    public class Check
    {
        public static bool ExistsInArray(int[] ints, int val)
        {
            if (ints.Contains(val)) return true;
            else return false;
        }
    }

现在我在这里没有看到任何问题,因为代码工作正常但不知何故我仍然没有通过测试,因为一旦数组包含一百万个值,这“不够快”。

我自己写的唯一代码是:

    if (ints.Contains(val)) return true;
    else return false;

我得到的其他代码。

有没有办法加快这个过程?

提前致谢。

编辑: 我看到一个页面,其中显然有人进行了与我进行的测试相同的测试,这似乎归结为节省了 CPU 周期。

引用:How to save CPU cycles when searching for a value in a sorted list?

现在他在方法中的解决方案是:

    var lower = 0;
    var upper = ints.Length - 1;

    if ( k < ints[lower] || k > ints[upper] ) return false;
    if ( k == ints[lower] ) return true;
    if ( k == ints[upper] ) return true;

    do
    {
        var middle = lower + ( upper - lower ) / 2;

        if ( ints[middle] == k ) return true;
        if ( lower == upper ) return false;

        if ( k < ints[middle] )
            upper = Math.Max( lower, middle - 1 );
        else
            lower = Math.Min( upper, middle + 1 );
    } while ( true );

现在我明白了这段代码是如何工作的,但我不清楚为什么这应该更快。如果有人可以详细说明会很好。

最佳答案

如果它是排序的数组,你可以使用BinarySearch来加速这个过程

public static bool ExistsInArray(int[] ints, int val)
{
    return Array.BinarySearch(ints, val) >= 0;
}

关于c# - 如何加快循环百万值数组的过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56991384/

相关文章:

c# - 尝试反序列化 JSON 时获取 NullReferenceException

c# - 在 SaveDialog 中强制扩展

c# - 在 asp.net mvc 中按查询字符串搜索

c++ - std::array<const T, n> 与 std::array<T, n> 重载解析

c# - 使用 jQuery AJAX 将字符串数组传递给具有可变数量参数的 web 方法

python - 遍历 numpy.array 的任意维度

c# - Microsoft.NETCore.UniversalWindowsPlatform 引用的用途是什么?

c - 如何检查字符串是否在 C 中的字符串数组中?

c# - 循环遍历泛型类的子类

c# - 如何增量迭代大小为 n 的字节数组的所有可能值?