C 数组中最长的 1 序列
我有一个像这样的数组:
0011011100011111001
我想找到这个数组中最长的 1 序列,记下起始点的长度和位置,这里长度为 5,起始点为 12。
有什么想法吗怎么办?
I have an array like this:
0011011100011111001
I'd like to find the longest sequence of 1's in this array, keeping note of the length and position of the starting point, here the length would be 5 and the starting point is 12.
Any ideas for how to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意这看起来像家庭作业,但我要做的方法是存储当前 1 的运行和最长运行的开始和长度。迭代数组。每当从 0 变为 1 时,更新当前起始位置并将长度设置为 1。当长度大于最长时,更新最长长度和起始点。就输入的长度而言,其运行时间复杂度为 O(n)。这不包括边缘情况,例如没有 1 的数组。
I agree that it looks like homework, but the way I would do it is to store the start and length of the current run of 1's and that of the longest run. Iterate through the array. Whenever you change from a 0 to a 1, update the current start position and set length to 1. When the length is longer than the longest, update the longest length and start point. This runs in O(n) in the length of the input. This doesn't cover edge cases such as an array with no 1's.
迭代数组,保留迄今为止找到的最大连续数的计数,以及当前连续数的单独计数。
稍微思考一下,您应该能够自己弄清楚如何跟踪起始位置。
Iterate over the array, keeping a count of the maximum number of consecutive ones found so far, and a separate count of the current number of consecutive ones.
With a bit of thought, you should be able to figure out for yourself how to track the starting position.
您可以将起始位置和长度最初设置为零,然后逐一遍历数组元素,使用简单的状态机跟踪
1
和0
之间的转换。状态表如下所示:
由于您只对
1
序列感兴趣,因此初始状态将lastNum
设置为零以确保1
在开始时正确开始运行。我们还将初始的“迄今为止最大的运行”设置为大小和位置为零,以确保它被第一次真实运行覆盖。此方法有一个特殊的边缘情况,因为我们必须检测列表中的最终数字是否为
1
- 如果是,则意味着不会有1 -> 。 0
转换位于列表末尾,用于检查1
数字的最终运行。由于我们将在不检查最终运行的情况下退出循环,因此我们会进行最终检查,就像我们从
1
转换到0
一样。伪代码是这样的。首先,初始化所有变量:
然后我们可以简单地迭代列表中的每个数字并按照上图检测转换:
然后,最后,处理上述边缘情况:
You can set a starting position and length initially to zero, then go through the array elements one by one, keeping track of the transitions between
1
and0
with a simple state machine.The state table looks like this:
Since you're only interested in
1
sequences, the initial state haslastNum
set to zero to ensure a1
at the start correctly begins a run. We also set up the initial "largest run to date" to have a size and position of zero to ensure it gets overwritten by the first real run.There's a special edge case to this method because we have to detect if the final number in the list is
1
- if so, it means there will have been no1 -> 0
transition at the end of the list for checking the final run of1
numbers.Since we will have exited the loop without checking that final run, we do a final check as if we were transitioning from
1
to0
.The pseudo-code goes something like this. First, the initialisation of all variables:
Then we can simply iterate over each number in the list and detect transitions as per the diagram above:
Then, finally, handling of the afore-mentioned edge case: