fork download
  1. /* Count frequency of each element*/
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class Ideone
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. Scanner sc = new Scanner(System.in);
  12. int size = sc.nextInt();
  13. // now we are constructing input array and then populating it.
  14. if(size==0) {
  15. System.out.println("We cant check freq for empty array!");
  16. return;
  17. }
  18. // declare array
  19. int[] arr = new int[size];
  20. // our code will do work even if arr[i]<0 elemnt
  21.  
  22. for(int idx=0; idx<size; idx++){
  23. arr[idx] = sc.nextInt();
  24. }
  25. // now constructing our boolean array
  26. boolean[] vis = new boolean[size];
  27.  
  28. Arrays.fill(vis, false);
  29. // vis = [false, false, ... false];
  30.  
  31. // do my main logic
  32. for( int i=0; i<size; i++ ){
  33. //check if that index is already visited
  34. if(vis[i]==false){
  35. // ye hi to main chij bhulgaya tha
  36. //agar wo indx encounterned nahi hai already to usko
  37. // true/ visited mark karna hi hoga!
  38. vis[i]=true;
  39. int count=1;
  40. for(int j=i+1; j<size; j++){
  41. if(arr[i]==arr[j]){
  42. vis[j] = true;
  43. count++;
  44. }
  45. }
  46. System.out.println("Frequency of "+arr[i]+" is = "+ count);
  47. }
  48. }
  49. return;
  50.  
  51. }
  52. }
Success #stdin #stdout 0.18s 60576KB
stdin
10
1
3
5
1
9
10
5
3
5
5
stdout
Frequency of 1 is = 2
Frequency of 3 is = 2
Frequency of 5 is = 4
Frequency of 9 is = 1
Frequency of 10 is = 1