我有以下带有 0 和 1 的向量:
test1 <- c(rep(0,20),rep(1,5),rep(0,10),rep(1,15))
test1
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
^
test2 <- c(rep(0,8),rep(1,4),rep(0,5),rep(1,5),rep(0,6),rep(1,10),rep(0,2))
test2
[1] 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0
^
我需要找到最后一个 1 序列中第一个 1 的索引(在上面的代码中用 ^ 表示)。我有一个解决方案(如下),但性能不佳,我该如何提高性能?
For test1
and test2
, the 预期产出分别是36和29。
这是一个次优解决方案:
temp1 <- cumsum(test1)
which(temp1==max(temp1[duplicated(temp1)&temp1!=max(temp1)]+1))[1]
[1] 36
temp2 <- cumsum(test2)
which(temp2==max(temp2[duplicated(temp2)&temp2!=max(temp2)]+1))[1]
[1] 29
注意:实际向量的长度约为 10k。