Q.Given an array of size 1000 having no's between 1 to 9. Find the number of times each element is repeated in the most efficient way?



                                package com.manish;

                                import java.util.Arrays;

                                public class OccurenceOfNumber 

                                 {


public static void main(String[] args)

{

int arr[]={2,5,8,9,2,1,1,5,5};

Arrays.sort(arr);

for(int i=1;i<arr.length;i++)

{

int low=binarySearchFirst(arr,i);

int high=binarySearchLast(arr,i);

int total=(high>=low && high!=-1 && low!=-1)?(high-low+1):0;

System.out.println(i+" : "+total+" times");

}

}

public static int binarySearchFirst(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid]< k)

{

begin=mid+1;

}

else{

end=mid-1;

}

}

return (begin<=end && begin>=0 && arr[begin]!=k)? -1:begin;

}

public static int binarySearchLast(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid] > k)

{

end=mid-1;

}

else {

begin=mid+1;

}

}

return (end>=begin && end>=0 && arr[end]!=k)? -1:end;

}

                                  }


No comments:

Post a Comment