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) = 5
target (int) = 2
Return:
(int) 3
Example 2
Input:
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 2
Return:
(int) 0
Example 3
Input:
nums (int[]) = [4,4,4,4]
size (int) = 4
target (int) = 4
Return:
(int) 4

Because 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 count
Run your code to see the result.