How do I increase the algorithm performance for longer array of numbers?

后端 未结 2 426
傲寒
傲寒 2021-01-29 07:05

Thanks for looking.

Count how many numbers are less than 4 in an ordered array of numbers.

How do I increase the algorithm performance for longer array

2条回答
  •  故里飘歌
    2021-01-29 07:17

    You should use Array.BinarySearch

    static int CountNumbers(int[] sortedArray, int lessThan)
    {
        if (sortedArray[0] >= lessThan) return 0;
    
        int lengthOfArray = sortedArray.Length;
        if (lengthOfArray == 0) return 0;
        if (sortedArray[lengthOfArray - 1] < lessThan) return lengthOfArray;
    
        int index = Array.BinarySearch(sortedArray, lessThan);
        if (index < 0)
            return ~index;
        // Find first occurrence in case of duplicate
        for (; index > 0 && sortedArray[index - 1] == lessThan; index--) ;
        return index;
    }
    

提交回复
热议问题