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

后端 未结 6 1406
不思量自难忘°
不思量自难忘° 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

    class Answer
    {
        public static bool Exists(int[] ints, int k)
        {
            int index = Array.BinarySearch(ints, k);
            if (index > -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        static void Main(string[] args)
        {
            int[] ints = { -9, 14, 37, 102 };
            Console.WriteLine(Answer.Exists(ints, 14)); // true
            Console.WriteLine(Answer.Exists(ints, 4)); // false
        }
    
    }
    

提交回复
热议问题