且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何检查是否INT []中只包含某些数字?

更新时间:2023-11-25 23:35:10

您不能没有通过它遍历检查数组。因此, O(N)是你会得到***的。另一种解决办法是控制加载阵列,并抛出一个异常,当有人试图把一个值不是 0 1 在里面。另一种解决方案可能是使用布尔[] 其中只有两个可能的值,无论如何,但需要一定的转换,如果你确实需要的数字。 (注意:如果你需要两个以上的值,它可能是有意义的看一个枚举,特别是如果这些值都应该重新present的的东西的)

此外,,因为你不得不检查整个阵列(没有提前退场)其中,不是***的解决方案在这里。使用任何来代替(但它仍然在做基本上是你的for循环做的 - ***的情况下 O(1),更糟糕 O(N)平均 O(N))。

 如果(myArray.Any(A =>在= 0&安培;!&安培;!A = 1))
{
     // ....
}

I need to check that an int[] contains only certain values (in this case 0s & 1s) and throw an exception if it doesn't.

Is there a more efficient way to do it than either of the following solutions?

Simple (but O(n)):

for(int n = 0; n < myArray.Length; n++)
    if(!(myArray[n] == 0 || myArray[n] == 1))
        throw new Exception("Array contains invalid values");

Using Where():

if(myArray.Where(n => !(n==1 || n==0)).ToArray().Length > 0)
    throw new Exception("Array contains invalid values");

You can't check an array without iterating through it. So O(n) is the best you are going to get. The other solution would be to control loading the array and throw an exception when somebody tries to put a value that isn't 0 or 1 in it. Another solution might be to use a bool[] which only has two possible values anyway, but would require some conversion if you actually need numbers. (Note: if you needed more than two values, it might make sense to look at an enum, especially if those values are supposed to represent something)

Also, Where is not the best solution here because you are forced to check the whole array (no early exit). Use Any instead (but it's still doing basically what your for loop is doing - best case O(1), worse O(n) average O(n)).

if (myArray.Any(a => a != 0 && a != 1))
{
     // ....
}