我將演示如何使用列表中做到這一點:
L = [21, 17, 16, 7, 3, 9, 11, 18, 19, 5, 10, 23, 20, 15, 4, 14, 1, 2, 22, 13, 8, 12, 6]
長度爲N=23
和W = 4
。
讓你列表的兩個新副本:
L1 = [21, 17, 16, 7, 3, 9, 11, 18, 19, 5, 10, 23, 20, 15, 4, 14, 1, 2, 22, 13, 8, 12, 6]
L2 = [21, 17, 16, 7, 3, 9, 11, 18, 19, 5, 10, 23, 20, 15, 4, 14, 1, 2, 22, 13, 8, 12, 6]
環路從i=0
到N-1
。如果i
不能被W
整除,則用max(L1[i],L1[i-1])
替換L1[i]
。
L1 = [21, 21, 21, 21, | 3, 9, 11, 18, | 19, 19, 19, 23 | 20, 20, 20, 20 | 1, 2, 22, 22 | 8, 12, 12]
環路從i=N-2
到0
。如果i+1
不能被W
整除,則將L2[i]
替換爲max(L2[i], L2[i+1])
。
L2 = [21, 17, 16, 7 | 18, 18, 18, 18 | 23, 23, 23, 23 | 20, 15, 14, 14 | 22, 22, 22, 13 | 12, 12, 6]
製作長度N + 1 - W
列表L3
,使L3[i] = max(L2[i]
,L1[i + W - 1])
L3 = [21, 17, 16, 11 | 18, 19, 19, 19 | 23, 23, 23, 23 | 20, 15, 14, 22 | 22, 22, 22, 13]
然後這個名單L3
是你所尋求的移動最大值,L2[i]
是i
和未來之間的最大範圍垂直線,而l1[i + W - 1]
是垂直線和i + W - 1
之間的最大範圍。
這麼好,我不得不贊同這個答案和你引用的答案! – Andy 2012-01-18 05:31:12
我必須在這裏評論說,雙棧隊列實現不一定是最好的。我試過了,對於一個實時應用程序,結果是災難性的......根據應用程序,人們也可以嘗試deque(雙端隊列)結構,它也會給出O(N)結果,但不一定爲O(1)攤銷操作。我在數組上實現了一個循環deque,它運行良好。看看這個問題以及:https://stackoverflow.com/questions/12329073/find-the-min-number-in-all-contiguous-subarrays-of-size-l-of-a-array-of-size -n。 – Alan 2017-09-18 00:41:05