简体   繁体   中英

Efficient algorithm for finding how many times x appears in a sorted array

I was given a sorted array of n integer values and an integer x. What would be the most efficient algorithm for finding how many times x appears in this array?

I thought about binary search and when I get to x then I split left and right to see if there is more x to add to my count, but I wanted to know if there is any other solution for this.

Well, if the number of occurrences of x in the array can be considered a constant compared to the length of the array, your binary search approach would give you an O(log(N) algorithm, and you can't do better than that.

However, if, for example, all the elements of your array are x , or half the elements are x , the second part of your algorithm ( split left and right to see if there is more x to add to my count ) will take linear time.

You can avoid that if you use two more binary searched to find the indices of the first x and last x in the array. You can do it, for example, by running a binary search on x-1 and x+1 (assuming this is an int array).

This will give you O(log(N)) running time regardless of how many x s are in the array.

it's integers and the list is sorted.

Use a splitting search algorithm where you split at index:

indexToSplit = (int) x*(an - a1)/n

Where:

x is your integer to find
an is the last integer in the list
a1 is the first integer in the list
n is the size of the list

Assuming your list is sorted from lowest to highest

This is a heuristic which can be better than binary sort, but depends on how uniformly the integers in the list are distributed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM