The idea is to check for following two conditions. If following two conditions are true, then return true. 1) max – min + 1 = n where max is the maximum element in array, min is minimum element in array and n is the number of elements in array. 2) All elements are distinct.
import java.util.ArrayList;
import java.util.HashMap;
public class ArrayConsecutive {
public static void main(String[] args){
int a[]={1,2,3,4,5,6,7,8,9,10,10};
ArrayList<Integer> b=new ArrayList<Integer>();
int max=findmax(a);
int min=findmin(a);
if(max-min+1 != a.length)
System.out.println("Not consecutive");
else {
if(!Distinct(a))
System.out.println("Not consecutive");
else
System.out.println("Given array elements are consecutive");
}
}
public static int findmax(int[] a){
int max=a[0];
for(int i=1;i<a.length;i++)
if(max < a[i])
max=a[i];
return max;
}
public static int findmin(int[] a){
int min=a[0];
for(int i=1;i<a.length;i++)
if(min > a[i])
min=a[i];
return min;
}
public static boolean Distinct(int a[])
{
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
Integer count;
for(int i=0;i<a.length;i++){
count=map.get(a[i]);
if(count==null)
map.put(a[i], (count==null?1:count++));
else{
if(count==1)
return false;
}
}
return true;
}
}
No comments:
Post a Comment