8. How Many Times

A survey asked customers to rate a product by choosing a whole number. The team wants to know how popular one particular rating was.

Write a method countOccurrences that takes the array nums of submitted ratings and an integer target, and returns how many times target appears in nums. If it never appears, return 0.

Example 1

Input:
nums = [5,3,5,4,5], target = 5
Output:
3
Explanation:

The rating 5 was chosen three times.

Example 2

Input:
nums = [1,2,3], target = 9
Output:
0
Explanation:

Nobody chose 9, so the count is 0.

Constraints

1 ≤ nums.length ≤ 1000

-1000 ≤ nums[i], target ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…