java 计算列表中有多少个有序值

ahy6op9u  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(101)

代码如下:

public static int countConsecutiveGroups(List<Integer> list) {
    int count = 0;
    int consecutiveCount = 1;

    for (int i = 1; i < list.size(); i++) {
        if (list.get(i).equals(list.get(i - 1))) {
            consecutiveCount++;
        } else {
            consecutiveCount = 1;
        }

        if (consecutiveCount == 5) {
            count++;
            consecutiveCount = 0; // Reset the count for the next group
        }
    }

    return count;
}

我有下面的问题,当给它一个升序排列的数字列表时,例如。[1,2,3,4,5,6,7...]它返回从最低到最高有五个连续值。但是,如果我给予它一个列表,它也是有序的,但有重复的值,例如[1,1,2,3,3,3,4,4,5,5...],它不会返回有一个有序的数字序列。
我想让它返回五个数的有序序列有多少个。

e.g. [1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5] // This should return me 2 

// Because there are the following stairs.
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

// And the original list subtracting these two ordered lists should be:
[1, 3, 4]
mm9b1k5b

mm9b1k5b1#

代码中有一个错误:如果有6个或更多数字的序列,也会启动count++操作。事实上,当有6个或更多数字的序列时,变量cumultiveCount的值会达到5。

相关问题