702769. Count Number
Medium
Count Number
Slug: count-number4832
Difficulty: Medium
Id: 702769
Topic Tags: Arrays, Data Structures
Company Tags: None
Summary
This problem involves counting the number of occurrences of a specific target element in an unsorted array. The key concepts involved are arrays and data structures.
Detailed Explanation
Given an unsorted integer array arr and an integer k, write a function to count the number of times k appears in the array.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto 0, which will store the frequency ofk. - Iterate through each element
xin the array. - If
xis equal tok, increment thecountby 1. - Return the final value of
count.
The time complexity of this solution is O(n), where n is the length of the input array, because we need to traverse the entire array once. The space complexity is O(1), as we only use a constant amount of space to store the count.
Optimized Solutions
Java
public int countNumber(int[] arr, int k) {
int count = 0;
for (int x : arr) {
if (x == k) {
count++;
}
}
return count;
}