Count duplicate numbers (with.Java)
This is an article about the “Number of duplicate numbers (with.Java)” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
When an array containing integers and an integer n are given as parameters, complete the solution function to return how many n are in the array.
Restrictions
- 1 ≤ length of array ≤ 100
- 0 ≤ element of array ≤ 1,000
- 0 ≤ n ≤ 1,000
Input/Output Example
array | n | result |
---|---|---|
[1, 1, 2, 3, 4, 5] | 1 | 2 |
[0, 2, 3, 4] | 1 | 0 |
My solution to the problem
class Solution {
public int solution(int[] array, int n) {
int answer = 0;
for(int i = 0; i < array.length; i++){
if(array[i] == n){
answer++;
}
}
return answer;
}
}
Solution explanation
The solution was solved by sequentially comparing the value of n starting from index 0 and increasing the value of the answer by 1 if the value is found.