//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;
}
}
const getMissingNumbers = (list) => {
if (!list || list.length === 0) return [];
const missing = [];
// sort the list
list.sort((a, b) => a - b);
// pin start and end points in the list
const step = list[0];
const last = list[list.length - 1];
for (let i = step; i < last; i++) {
if (list.indexOf(i) === -1) missing.push(i);
}
return missing;
}
4条答案
按热度按时间zbsbpyhn1#
如果你保证数组是有序的,没有任何重复,那么你可以在O(1)中检查它
我认为这段代码应该能在这个特定的情况下工作:)
3yhwsihp2#
此方法首先检查“简单”的情况,然后迭代数组以检查更复杂的情况。
jvidinwx3#
遍历数组并检查当前项是否正好比当前索引大
x
,其中x
是数组中的第一个元素。mqxuamgl4#
更简单可靠的方法: