我们给出n个元素和整数k的阵列。假设我们希望长度为k的一个窗口在阵列上滑动,报告包含在每个窗口中的最大值。例如,给定阵列
15 10 9 16 20 14 13由于长度为4的窗口,我们将输出
[15 10 9 16] 20 14 13 - >输出16 15 10 9 16 20] 14 13 --->输出20 15 10 9 16 20 14 13 - >输出20 15 10 9 16 20 14 13] --->输出20因此,结果将是
16 20 20 20我快到通过跟踪在每个点窗口的最大元素的问题,但遇到了一个问题,当最大的元素被滑出窗外。在这一点上,我想不出一个快速的方法来找出现存最大的因素是什么。
有谁知道一个高效的算法来解决这个问题?
解决方案This旧的问题 讨论如何建立一个队列中的数据结构支持插入,出列,并找到分钟都在O(1)时间。注意,这是不会标准的优先级队列,而是在其中的任何一点,你可以找到它包含了O(1)时间的最小元素的值的队列。你可以很容易地修改这个结构,支持找到-Max在O(1),而不是找分钟,因为这是更贴近这个特殊的问题。
利用这种结构,可以按如下方式解决O(n)的这个问题时间:
这总共需要O(n)的时间,因为你访问的每个数组元素一次,和入队各出队最多一次,调用find-MAX恰好n-k次。我认为这是pretty爽,因为复杂的独立的k个的,它不最初看起来像它一定是可能的。
希望这有助于!并感谢问一个很酷的问题!
We are given an array of n elements and an integer k. Suppose that we want to slide a window of length k across the array, reporting the largest value contained in each window. For example, given the array
15 10 9 16 20 14 13Given a window of length 4, we would output
[15 10 9 16] 20 14 13 ---> Output 16 15 [10 9 16 20] 14 13 ---> Output 20 15 10 [ 9 16 20 14] 13 ---> Output 20 15 10 9 [16 20 14 13] ---> Output 20So the result would be
16 20 20 20I was approaching the problem by keeping track of the maximum element of the window at each point, but ran into a problem when the largest element gets slid out of the window. At that point, I couldn't think of a fast way to figure out what the largest remaining element is.
Does anyone know of an efficient algorithm for solving this problem?
解决方案This older question discusses how to build a queue data structure supporting insert, dequeue, and find-min all in O(1) time. Note that this is not a standard priority queue, but instead is a queue in which at any point you can find the value of the smallest element it contains in O(1) time. You could easily modify this structure to support find-max in O(1) instead of find-min, since that's more relevant to this particular problem.
Using this structure, you can solve this problem in O(n) time as follows:
This takes a total of O(n) time, since you visit each array element once, enqueuing and dequeuing each at most once, and calling find-max exactly n-k times. I think this is pretty cool, since the complexity is independent of k, which doesn't initially seem like it necessarily should be possible.
Hope this helps! And thanks for asking a cool question!
更多推荐
如何找到最大的一些固定的给定长度的每个子阵列的给定数组中
发布评论