array = [-9,-1,2,0,5,-6,7,-8,0,-1]
这里在数组中我需要找到最大交替切片的长度( - 到+或+到 - ) 0是+ ve或-ve
所以对于上面的数组,答案是8,因为slice(1,7)长度是最大的交替切片
空间复杂度:O(1) 时间复杂度:O(N)
答案 0 :(得分:2)
这是一种可视化正在发生的事情的快速方法
data = [-9, -1, 2, 0, 5, -6, 7, -8, 0, -1]
is_pos = [n >= 0 for n in data] # [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]
is_neg = [n <= 0 for n in data] # [1, 1, 0, 1, 0, 1, 0, 1, 1, 1]
from itertools import cycle
alt = cycle([0, 1])
alt_pos = [n ^ a for n,a in zip(is_pos, alt)] # [0, 1, 1, 0, 1, 1, 1, 1, 1, 1]
alt_neg = [n ^ a for n,a in zip(is_neg, alt)] # [1, 0, 0, 0, 0, 0, 0, 0, 1, 0]
# you are looking for the longest run of 0s or 1s
对于O(1)空间,O(n)时间算法:
所以你的算法看起来像
# state variables
pos_run_len = 0
neg_run_len = 0
longest_run_len = 0
for n in data:
# update variables based on value of n
# when finished, longest_run_len == 8