如何找到序列中的连续数字
how to find consecutive numbers in a sequence
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
相关文章:
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 如何在 c++ 中检查连续片段中数字被 11 整除
- C++ 如何找出数组中最多的连续数字?
- 如何制作 arduino 串行循环(连续接收数字)
- 在随机生成的数组中查找重复的连续数字
- 子数组中两个数字的相同出现(连续)
- 在向量中找到连续数字的更有效方法
- 连续两次写入数字时出现逻辑错误 (C++)
- 不理解连续数字之间的空格代码
- 我如何限制我连续拥有的数字数量
- 给定n个数字,编写一个例程,以在4个连续数字之间找到最大的数字
- 从输入中找到连续十六进制数字的最大数量
- 在序列中查找相似的数字并记录最大连续连胜
- 如何生成没有两个相邻连续数字的排列
- 随机顺序的连续数字
- 返回连续数字的逻辑假设数组包含元素 1,9,2,3,4,9,6,7,8,那么它应该返回 2,3,4,6,7,8
- 非连续内部数字表示上的位移位
- 如何找到序列中的连续数字
- 连续获取 2 个唯一数字
- 在一个有连续数字的向量中找到一个数字