Count Frequency in a range
import java.util.HashMap;
public class Solution {
public static int[] countFrequency(int n, int x, int []nums){
HashMap<Integer,Integer> mp = new HashMap<>();
int result[] = new int[n];
for(int i=0; i<nums.length; i++)
{
int freq = 0;
if(mp.containsKey(nums[i]))
{
freq = mp.get(nums[i]);
}
freq += 1;
mp.put(nums[i],freq);
}
for (int i = 0; i < n+1; i++) {
mp.putIfAbsent(i, 0);
}
for(int i=0; i<n; i++)
{
result[i] = mp.get(i+1);
}
return result;
}
}
No comments:
Post a Comment