问题
I have a Long array with these numbers:
long[] = {1,2,3,5,6,7};
Notice that 4 is missing.
What's the best way to test this array if any such gaps exist or not?
回答1:
If you're guaranteed that arrays is ordered without any duplicate then you could check that in O(1)
I think this code should work in this specific case :)
//assume that given array is ordered and has no duplicated value
long[] myarray = {5,6,7}; //no gap
long[] myarray1 = {1,2,4}; //has gap
long[] myarray2 = {10,11,12,13,14,15}; //no gap
//return true if has gap
//return false if no gap
//throw null-pointer if empty
public static boolean checkIfHasGap(long[] array) {
if (array.length == 0) {
throw new NullPointerException("Given Array is empty");
} else {
return array[0] + array.length != array[array.length - 1] + 1;
}
}
回答2:
public static boolean hasGaps(long[] array) {
if (array == null || array.length == 0) {
return false;
}
if (array[array.length - 1] - array[0] + 1 != array.length) {
return true;
}
for (int i = 1; i < array.length; i++) {
if (array[i] != array[i - 1] + 1) {
return true;
}
}
return false;
}
This method first check for the "easy" cases, then iterate the array to check the more complex cases.
回答3:
Loop through the array and check, if the current item is exactly x more than the current index, where x is the first element in your array.
public boolean hasGaps(long[] array) {
if(array == null || array.length == 0) {
return false;
}
long start = array[0];
for(int i = 0; i < array.length; i++) {
if(array[i] != i + start) {
return true;
}
}
return false;
}
来源:https://stackoverflow.com/questions/30053354/how-to-check-if-an-array-of-numbers-has-gaps