public class CheckArrayIsConsecutive {
static boolean checkConsecutive(int[] arr){
int min = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(min>arr[i]){
min = arr[i];
}
}
for(int i=0;i<arr.length;i++){
if(Math.abs(arr[i])-min>=arr.length){ //means array size small than required consecutive element
return false;
}
if(arr[Math.abs(arr[i])-min]<0){ //if we want to store negative at index there already a negative value
return false;
}
arr[Math.abs(arr[i])-min] = - arr[Math.abs(arr[i])-min];
}
return true;
}
public static void main(String[] args) {
int[] arr = {77,78,76,75,72,73,74};
boolean bool = checkConsecutive(arr);
System.out.println(bool);
}
}
output: true
if input below then output false:
int[] arr = {77,78,76,75,72,73,79};
ref: https://github.com/mission-peace/interview/blob/master/src/com/interview/array/CheckIfArrayElementsAreConsecutive.java
No comments:
Post a Comment