Last active
August 29, 2015 14:06
-
-
Save senvey/6918e70557288aba60f6 to your computer and use it in GitHub Desktop.
Find the count of given number in a sorted array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def count(array, n): | |
# starting point | |
left, right = 0, len(array) | |
while left < right: | |
mid = (left + right) / 2 | |
if array[mid] >= n: | |
right = mid | |
else: | |
left = mid + 1 | |
# before exiting the loop, right points | |
# to the given number if any: | |
# array[right] >= n | |
start = right | |
# ending point | |
left, right = 0, len(array) | |
while left < right: | |
mid = (left + right) / 2 | |
if array[mid] <= n: | |
left = mid + 1 | |
else: | |
right = mid | |
# before exiting the loop, left points | |
# to the immediate right of given number | |
# if any: array[left - 1] <= n | |
end = left | |
return end - start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment