Problem
Given a sorted array of integers and a target
element. Find the number of occurrences of the target
in the array. You must write an algorithm with O(log n)
runtime complexity.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Binary Search
This problem is a variation of the problem Find first and last positions of target element in sorted array. If we can find the first and last position of the target element in the array, then we can easily find the count which will be equal to lastPosition - firstPosition + 1
Code
|
|
Complexity
- ⏰ Time complexity:
O(log n)
wheren
is number of elements in the array - 🧺 Space complexity:
O(1)