Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

c# - sorted search increase performance

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

Implement function CountNumbers that accepts a sorted array of integers and counts the number of array elements that are less than the parameter lessThan.

For example, SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4) should return 2 because there are two array elements less than 4.

I have entered:

public class SortedSearch
{
    public static int CountNumbers(int[] sortedArray, int lessThan)
    {
         int returnedValued = 0;

            foreach (int i in sortedArray)
            {
                if(i<lessThan)
                returnedValued += 1;
            }

            return returnedValued;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(SortedSearch.CountNumbers(new int[] { 1, 3, 5, 7 }, 4));
    }
}

I was wondering why this was marked as difficulty level hard and expected time 20 min when I knew it should only take a few. Anyway, 2 out of 4 cases passed. I'm failing on time limit exceeded and I'm guessing I need to refactor to return a faster search. Is this right? And if so could anyone help with it?

      Example case: Correct answer 
      Various small arrays: Correct answer 
      Performance test when sortedArray contains lessThan: Time limit exceeded 
      Performance test when sortedArray doesn't contain lessThan: Time limit exceeded
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This passed all 4 tests:

public static int CountNumbers(int[] sortedArray, int lessThan)
{
    int val = Array.BinarySearch(sortedArray, lessThan);
    return val < 0 ? ~val : val;
}

As others have said, they expect you to use Array.BinarySearch which I didn't realise until read the 2nd hint.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...