Intermediate Level
Implement the countTargetInSortedArray method that counts how many times the target appears in a sorted array.
The input contains a sorted integer array nums, its length size, and an integer target. Your task is to count how many times target appears in the array.
For example, in [1,2,2,2,3], the value 2 appears three times, so the answer is 3. If the target is not found, return 0.
Example 1
Input
nums (int[]) =
[1,2,2,2,3]size (int) =
5target (int) =
2Returns (int)
3Example 2
Input
nums (int[]) =
[1,3,5]size (int) =
3target (int) =
2Returns (int)
0Example 3
Input
nums (int[]) =
[4,4,4,4]size (int) =
4target (int) =
4Returns (int)
4Because the array is sorted, all occurrences of the target will be together.
A simple solution is to scan the array and count every value equal to target. You may stop early after passing the target in a sorted array, but counting matches directly is enough for these inputs.
Pseudocode:
function countTargetInSortedArray(nums, size, target):
count = 0
for i from 0 to size - 1:
if nums[i] == target:
count++
return countReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run