如何检查数字数组是否有间隔? [英] How to check if an array of numbers has gaps?

查看:87
本文介绍了如何检查数字数组是否有间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下数字的Long数组:

I have a Long array with these numbers:

long[] = {1,2,3,5,6,7};

请注意,缺少4. 是否存在这种差距,测试此数组的最佳方法是什么?

Notice that 4 is missing. What's the best way to test this array if any such gaps exist or not?

推荐答案

如果可以保证数组的排序没有重复,则可以在O(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;
    }
}

这篇关于如何检查数字数组是否有间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆