简体   繁体   English

检查号码列表是否连续

[英]Check whether list of number is sequential or not

I have quite a layman question about Java programming. 我对Java编程有一个门外汉的问题。

I would like to write a function to check whether a list of number is sequential or not. 我想编写一个函数来检查数字列表是否是连续的。

Say [1, 2, 3, 4, 5], the function will return true, 说[1、2、3、4、5],该函数将返回true,

but for [1, 3, 4, 9, 10], the function will return false. 但是对于[1、3、4、9、10],该函数将返回false。

Could anyone help me? 有人可以帮我吗?

Thank so much! 非常感谢!

Write a loop that looks at each element of the list. 编写一个循环,查看列表中的每个元素。

For each position i in the list, test that list i + 1 equals list i + 1 . 对于列表中的每个位置i ,测试列表i +1是否等于列表i +1

You can code it yourself as an exercise. 您可以自己将其编码为练习。 (Don't forget to deal with the edge cases ...) (别忘了处理极端情况...)


UPDATE: ... for people treating this problem as a learning exercise. 更新: ...对于将这个问题视为学习活动的人们。

A simple direct implementation approach is probably the best idea; 一个简单的直接实现方法可能是最好的主意。 eg @Joe's final answer. 例如@Joe的最终答案。 However, the simple approach doesn't always work well ... or at all: 然而,简单的方法并不总是能很好地工作……或根本没有:

  • Some Java List implementations have a get method that is O(N) . 一些Java List实现的get方法为O(N) That would lead to an O(N^2) algorithm overall. 总体上将导致O(N^2)算法。
  • Sometimes aa list can only be accessed using an iterator; 有时,只能使用迭代器来访问列表。 ie list.get(i) might not be an option. list.get(i)可能不是一个选择。

In such cases, you could implement the algorithm with one pass through the list using an iterator. 在这种情况下,您可以使用迭代器一次遍历列表来实现该算法。 You need to keep "the previous element" in variable, etcetera. 您需要在变量等中保留“上一个元素”。

Logic is simple. 逻辑很简单。 Just get the first number and check whether it matches with the next value. 只需获取第一个数字,然后检查它是否与下一个值匹配。 Like that check adjacent values. 像那样检查相邻的值。 Break if the condition fails at any point. 如果条件在任何时候失败,请中断。 The list will be sequential if all the if condition is true. 如果所有if条件都为true,则该列表将是连续的。

As Stephen C said, it is a very simple logic 正如史蒂芬·C(Stephen C)所说,这是一个非常简单的逻辑

int a[] = { 1, 2, 3, 4, 5,7 };
        boolean flag = true;
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i + 1] != a[i] + 1) {
                flag = false;
                break;

            }
        }
        System.out.println("Flag is " + flag);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM