0

我有一个关于 Java 编程的外行问题。

我想编写一个函数来检查数字列表是否是连续的。

说 [1, 2, 3, 4, 5],函数会返回 true,

但是对于 [1, 3, 4, 9, 10],该函数将返回 false。

有人可以帮我吗?

非常感谢!

4

3 回答 3

3

Write a loop that looks at each element of the list.

For each position i in the list, test that listi + 1 equals listi + 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; e.g. @Joe's final answer. However, the simple approach doesn't always work well ... or at all:

  • Some Java List implementations have a get method that is O(N). That would lead to an O(N^2) algorithm overall.
  • Sometimes a a list can only be accessed using an iterator; i.e. list.get(i) might not be an option.

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.

于 2013-03-13T03:02:08.003 回答
0

正如 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);
于 2013-03-13T03:29:18.640 回答
0

逻辑很简单。只需获取第一个数字并检查它是否与下一个值匹配。像那样检查相邻的值。如果条件在任何时候失败,则中断。如果所有 if 条件都为真,则列表将是连续的。

于 2013-03-13T03:07:51.893 回答