如何检查数字数组是否有间隔?

编程入门 行业动态 更新时间:2024-10-09 02:26:45
本文介绍了如何检查数字数组是否有间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含以下数字的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; } }

更多推荐

如何检查数字数组是否有间隔?

本文发布于:2023-11-30 18:24:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651056.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   间隔   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!