sorted search increase performance

前端 未结 4 509
野性不改
野性不改 2021-01-29 14:53

Running through exercises on testdome...currently looking at https://www.testdome.com/for-developers/solve-question/9877

Implement function CountNum

4条回答
  •  逝去的感伤
    2021-01-29 15:45

    They expect you to use the Array.BinarySearch method to get 100%.

    using System;
    
    public class SortedSearch
    {
        public static int CountNumbers(int[] sortedArray, int lessThan)
        {
            int lengthOfArray = sortedArray.Length;
            if (lengthOfArray == 0) return 0;
    
            if (sortedArray[0] >= lessThan) return 0;
            if (sortedArray[lengthOfArray - 1] < lessThan) return lengthOfArray;
    
            int index = Array.BinarySearch(sortedArray, lessThan);
            if (index < 0)
                return ~index;
    
            return index;
        }
    
        public static void Main(string[] args)
        {
            Console.WriteLine(SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4));
        }
    }
    

提交回复
热议问题