如何找到序列中的连续数字

how to find consecutive numbers in a sequence

本文关键字:连续 数字 何找      更新时间:2023-10-16

im试图编写一个接受10个随机整数的程序,并检查序列中是否有三个连续的数字。连续的数字可以按升序或降序排列。以下是一些示例,可以帮助您更好地理解:顺序示例:

2 9 8 3 20 15 9 6 4 24是,2 3和4是连续

16 21 3 8 20 6 3 9 12 19是,21 20和19是连续

我搞不清我的代码出了什么问题。这是我到目前为止的代码:

#include <iostream>
using namespace std;
int main()
{
int a[10];
int i,n;
int count=0;

cout << "Enter 10 numbers between 1 and 25" << endl;
for (i = 0; i < 10; i++)
{             cin >> a[i];
}

for (n=0; n<10; n++)
{
    for (i=1; i<10; i++)
    { 
        if (a[i]==a[n]+1)
        {cout<<endl<<a[i]<<endl;
        count++;}
    }
}
}

您的代码当前为O(N2),要使其工作,它将为O(N3

我宁愿使用一个O(N)的算法。

假设您只关心25个值,则可以从一个32位单词开始,并将该单词中的位设置为与输入的每个数字相对应(例如,word |= 1 << input_number;)。

然后取一个值7(它是三个连续的位集),并在该字中可能的位位置测试它,看看你是否在字中的任何地方设置了三个连续位。如果是这样的话,它们的设置位置告诉你找到了三个连续的数字。如果不是,那么输入中就没有连续的三个数字。

for (int i=0; i<32-3; i++) {
    int mask = 7 << i;
    if (word & mask == mask)
        // three consecutive bits set -> input contained i, i+1 and i+2
}

您的逻辑是错误的。当前代码所做的是检查是否存在任何两个连续的整数。要检查三个,您应该引入另一个嵌套循环。这将使时间复杂性为O(n^3)。

另一种可能的检查方法是首先对数组进行排序,然后检查连续元素。这将使运行时间为O(nlogn)。您可以使用内置的sort功能进行排序。

算法需要重新设计。事实上,你正在做的是说:

For each array element x
     See if another array element is x+1
         print out the array element that is x+1

加入更多的定制线路,看看发生了什么,比如

    if (a[i]==a[n]+1)
    {cout<<endl<<a[n]<<","<<a[i]<<endl;
    count++;}

一种可能的算法是,尽管速度较慢

For each array element x
     See if another array element is x+1
          See if another array element is x+2
             print out x, x+1, and x+2