Count occurrences of a number in a sorted array with duplicates