This is one of the favourite questions for the interview to asses for the logical ability
The Common Solution:
If we can sort this array then it will not require any collections.
The Common Solution:
class FrequencyCalc
{
static int arr[] = new int[]{1,1,1,2,2,3,3,5,6,7,9,9,0};
public static void main(String args[]){
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
for(int i=0; i<arr.length; i++){
if(h.containsKey(arr[i])){
h.put(arr[i], h.get(arr[i]) + 1);
} else {
h.put(arr[i], 1);
}
}
System.out.println(h);
}
}
Solution without Using any Collection:If we can sort this array then it will not require any collections.
class FrequencyCalc
{
static int arr[] = new int[]{1,1,1,1,1,2,2,3,3,5,6,7,9,9,0};
public static void main(String args[]){
Arrays.sort(arr);
int x = arr[0];
int count=0;
for(int i=0;i<arr.length;i++){
count++;
if(arr[i]!=x){
System.out.println(arr[i-1]+"\t"+count);
count=0;
x=arr[i];
continue;
}
}
}
}
Comments
Post a Comment