I'm studying for a test, and found this question.
You are given a sorted array of integers for example:
{-5, -5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 67, 67, 99}
Write a method:
Public static int count (int[] a, int x)
that returns the amount of times, number 'x' is in the array.
for example:
x = -5, it returns 2
x = 2, it returns 5
x = 8, it returns 0
I need to write it as efficient as possible, please don't give me the answer (or write it if you wish, but I won't look), my idea is to do a binary search, and then go both edges (backward and forward) of the value that I find and with the index numbers, return the correct answer, my questions are:
- is it the most efficient way?
- won't it be O(n) in the worst case? (when the array is filled with a single number) -
If so - then why should I do a binary search?