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

后端 未结 6 1408
不思量自难忘°
不思量自难忘° 2021-02-10 05:16

In CodinGame learning platform, one of the questions used as an example in a C# tutorial is this one:

The aim of this exercise is to check the presence of

6条回答
  •  离开以前
    2021-02-10 05:46

    Yes, I think that binary search O(log(N)) complexity v. O(N) complexity is the solution:

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

    since Array.BinarySearch return non-negative value if the item (k) has been found:

    https://msdn.microsoft.com/en-us/library/2cy9f6wb(v=vs.110).aspx

    Return Value Type: System.Int32 The index of the specified value in the specified array, if value is found; otherwise, a negative number.

提交回复
热议问题